FilipB
FilipB

Reputation: 67

Pandas replace only working with regex

I already found a workaround, but I'm still curious about what's going on:

When I try to do replace in Pandas like so:

merged4[['column1', 'column2', 'column3']] = merged4[['column1', 'column2', 'column3']].replace(to_replace='.', value=',')

It's not working. I tried all different variants with Inplace for example. I also did astype(str) since the columns were float64.

However, when I do:

merged4[['column1', 'column2', 'column3']] = merged4[['column1', 'column2', 'column3']].replace(to_replace='\.', value=',', regex=True)

It's working like charm.

Is something wrong?

Upvotes: 2

Views: 942

Answers (1)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

When you don't use regex=True the method will look for the exact match of the replace_to value. When you use regex=True it will look for the sub strings too. So your code works when you use that parameter. Example

When you dont use the regex=True parameter, the replace method will look for the exact match of the replace_to value in the series.

df = pd.DataFrame()
df['k'] = ['YoYo.','mins.s.s','sos.s.','.','mama.mia']
df['k'].replace('.',',')
0       YoYo.
1    mins.s.s
2      sos.s.
3           ,
4    mama.mia

When you use regex = True it even matches the substrings of the series and changes the strings

df = pd.DataFrame()
df['k'] = ['YoYo.','mins.s.s','sos.s.','.','mama.mia']
df['k'].replace('\.',',',regex=True)
0       YoYo,
1    mins,s,s
2      sos,s,
3           ,
4    mama,mia

Upvotes: 4

Related Questions