Pandas.replace not remove character from data

I have a pandas data frame with a character "in some places (Python 2.7). I want to delete all of "the data. I am using the following method:

data_frame.replace(to_replace'"', value = '')

However, the data frame remains the same and the action is not performed. Any advice on what the problem is would be very helpful.

+4
source share
4 answers

You can try replacewith regex=True:

import pandas as pd

df = pd.DataFrame({'ItemID': {0: 8988, 1: 8988, 2: 6547, 3: 6547}, 
                   'Description': {0: 'Tall Chair', 1: 'Tall Chair', 2: 'Big" Pillow', 3: 'Big Pillow'}, 
                   'Feedback': {0: 'I hated it""', 1: 'Best chair" ever', 2: 'Soft and amazing', 3: 'Horrific color'}})
print df
   Description          Feedback  ItemID
0   Tall Chair      I hated it""    8988
1   Tall Chair  Best chair" ever    8988
2  Big" Pillow  Soft and amazing    6547
3   Big Pillow    Horrific color    6547

print df.replace({'"': ''}, regex=True)
  Description          Feedback  ItemID
0  Tall Chair        I hated it    8988
1  Tall Chair   Best chair ever    8988
2  Big Pillow  Soft and amazing    6547
3  Big Pillow    Horrific color    6547
+2
source

You need to use the method str.replace Series

So:

data_frame.foo.str.replace(to_replace'"', value = '')

foo is the name of the column

> df
    foo
0  "bar"

> df.foo.str.replace('"', '')
0    bar
Name: foo, dtype: object

If you have a lot of columns, but it is better to answer @jezrael, I think:

for s in df:
    if df[s].dtype == "object": # to avoid converting non-string column into string
        df.loc[:,s] = df.loc[:,s].str.replace('"', '')
+1
source

inplace True data_frame:

data_frame.replace(to_replace'"', value = '', inplace=True)

data_frame = data_frame.replace(to_replace'"', value = '')
-1

The function replacereturns a new DataFrame with the replaced data. Try:

data_frame = data_frame.replace(to_replace='"', value='')
-1
source

All Articles