Pandas: replacing part of a string from elements in different columns

Viewed 87

I have a dataframe where numbers contained in some cells (in several columns) look like this: '$$10'

I want to replace/remove the '$$'. So far I tried this, but I does not work:

replace_char={'$$':''}

df.replace(replace_char, inplace=True) 
3 Answers

your code is (almost) right. this will work if you had AA:

replace_char={'AA':''}
df.replace(replace_char, inplace=True) 

problem is $$ is a regex and therefore you need to do it differently:

df['your_column'].replace({'\$':''}, regex = True)

example:

df = pd.DataFrame({"A":[1,2,3,4,5,'$$6'],"B":[9,9,'$$70',9,9, np.nan]})


    A   B
0   1   9
1   2   9
2   3   $$70
3   4   9
4   5   9
5   $$6 NaN

do

df['A'].replace({'\$':''}, regex = True)

desired result for columns A:

0    1
1    2
2    3
3    4
4    5
5    6

you can iterate to any column from this point.

An example close to the approach you are taking would be:

df[col_name].str.replace('\$\$', '')

Notice that this has to be done on a series so you have to select the column you would like to apply the replace to.

    amt
0  $$12
1  $$34

df['amt'] = df['amt'].str.replace('\$\$', '')
df

gives:

  amt
0  12
1  34

or you could apply to the full df with:

df.replace({'\$\$':''}, regex=True)

You just need to specify the regex argument. Like:

replace_char={'$$':''}

df.replace(replace_char, in place = True, regex = True) 

'df.replace' should replace it for all entries in the data frame.

Related