Home > Net >  Change values in DataFrame based on a dict
Change values in DataFrame based on a dict

Time:05-16

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:

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

CodePudding user response:

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
  • Related