Home > Software design >  How do I remove special character like "," within a string in a DataFrame?
How do I remove special character like "," within a string in a DataFrame?

Time:10-07

I have a dataframe as shown below of type: pandas.core.frame.DataFrame

newdf = pd.DataFrame([
    [0, "Hello, How are you?", 1],
    ["I wish, we could get it right", 0, 0],
    [0, "Hey there, hope you are doing well", 0]],
    columns=['Mon','Tue','Wed'])



newdf

|Mon                            |   Tue                              |  Wed |
|:------------------------------|:----------------------------------:|-----:| 
| 0                             |   Hello, How are you?              |  1   |
|I wish, we could get it right  | 0                                  |  0   |
|              0                |Hey there, hope you are doing well  |  0   |

I want to save it as CSV and upload in MySQL, but there are strings with "," in sentences

I want to replace all "," with either "" or "-"

I tried

newdf1 = newdf.replace(",","-")

No change in the dataframe

Please help in replacing characters within the string in a DataFrame.

I have used .replace() earlier to change the entire element of a cell and it worked, but now I want to read inside a string and perform operation.

CodePudding user response:

You have to first enable regex for substring match:

>>> newdf.replace(",", "-", regex=True)
                             Mon                                 Tue  Wed
0                              0                 Hello- How are you?    1
1  I wish- we could get it right                                   0    0
2                              0  Hey there- hope you are doing well    0
>>> 
  • Related