'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:

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


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Corralien