In pandas I need to fix a few values in dataframe column with some other values, I created a dictionary:
value2fixed= {"lala" : "dada", "howdy": "hoodie"}
and my dateframe df looks something like:
col_1 col_2
0 lala 500
1 mel 650
2 howdy 750
in col_1 I want to replace lala with dada and howdy with hoodie leaving mel just being mel. I was hoping to use df[col_1].map(value2fixed, na_action=None | 'ignore') but both na_action option values replace mel with NaN.
Within a dictionary I can use value2fixed.get(key, key) and I was hoping to use somethin equal inside the map functionality (without using a lambda), preferably with inplace=True.Any thoughts?
When map isn't an option, there's always replace;
df['col_1'] = df['col_1'].replace(value2fixed)
df
col_1 col_2
0 dada 500
1 mel 650
2 hoodie 750
The difference between map and replace is that map replaces "invalid" keys with NaNs - in contrast, replace does not touch them.
You can use replace with a nested dictionary:
df.replace({'col_1':value2fixed}, inplace=True)
>>> df
col_1 col_2
0 dada 500
1 mel 650
2 hoodie 750
The nested dictionary syntax reads as:
Nested dictionaries, e.g., {‘a’: {‘b’: nan}}, are read as follows: look in column ‘a’ for the value ‘b’ and replace it with nan.
From the docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With