Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change values in DataFrame based on a dict

I have a Pandas Dataframe, eg. like below:

   Name  Age  Papers
0   tom   10      12
1  nick   15       8
2  juli   14       8

And I have a dictionary:

d = {10: 11, 14: 30, 20: 44}

I want to change values in df, such that where Age matches any dictionary d key, Papers should have corresponding value. So, final result should look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   Name  Age  Papers
0   tom   10      11
1  nick   15       8
2  juli   14      30

>Solution :

You can use:

df['Papers'] = df['Age'].map(d).combine_first(df['Papers']).astype(int)

map replaces each Age using the dictionary, which adds NaN if the values are missing so we use combine_first to add the old values back.

Output:

   Name  Age  Papers
0   tom   10      11
1  nick   15       8
2  juli   14      30
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading