Skip to content Skip to sidebar Skip to footer

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[['column

Solution 1:

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

Post a Comment for "Pandas Replace Only Working With Regex"