Given that this is the top Google result when searching for "Pandas replace is not working" I'd like to also mention that:
replace does full replacement searches, unless you turn on the regex switch. Use regex=True, and it should perform partial replacements as well.
This took me 30 minutes to find out, so hopefully I've saved the next person 30 minutes.
Answer from Reddspark on Stack OverflowGiven that this is the top Google result when searching for "Pandas replace is not working" I'd like to also mention that:
replace does full replacement searches, unless you turn on the regex switch. Use regex=True, and it should perform partial replacements as well.
This took me 30 minutes to find out, so hopefully I've saved the next person 30 minutes.
You need to assign back
df = df.replace('white', np.nan)
or pass param inplace=True:
In [50]:
d = {'color' : pd.Series(['white', 'blue', 'orange']),
'second_color': pd.Series(['white', 'black', 'blue']),
'value' : pd.Series([1., 2., 3.])}
df = pd.DataFrame(d)
df.replace('white', np.nan, inplace=True)
df
Out[50]:
color second_color value
0 NaN NaN 1.0
1 blue black 2.0
2 orange blue 3.0
Most pandas ops return a copy and most have param inplace which is usually defaulted to False
This is genuinely driving me crazy.
I have a data frame of unit prices in string format i'm trying to get them to a float
item_df['Unit Price'] = item_df['Unit Price'].replace('$','')and all the '$' are still there.
THEN when I do this:
item_df['Unit Price'][1] = item_df['Unit Price'][1].replace('$','')The '$' is gone from that index ಠ_ಠ. What the hell is going on?? Am I taking crazy pills or missing some fundamental concept?
Any help would be much appreciated.
Thanks,
Why doesn't this replacement change absolutely all entries meeting criteria?
dataframe.replace() does not work on a subset of rows
How to apply replace to whole DataFrame like in Python?
BUG: Pandas DataFrame replace() doesn't work if the dataframe has nullable boolean columns
df['funding_total_usd'].replace({'-',0})Does not work.