Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix some pandas column values with a dictionary and leave the others?

Tags:

python

pandas

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?

like image 426
dr jerry Avatar asked Jan 24 '26 10:01

dr jerry


2 Answers

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.

like image 167
cs95 Avatar answered Jan 27 '26 01:01

cs95


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

like image 34
sacuL Avatar answered Jan 27 '26 00:01

sacuL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!