I have two dataframes with different sizes and I am trying to perform an addition of values from a common column found in both dataframes based on matching values in another common column. My first dataframe looks like this:
df1
JavaScript
x
7
1
ID name region earnings
2
101 Joseph A 100
3
102 Adam A 200
4
103 Clint C 150
5
104 Mark C 60
6
105 Michael A 0
7
df2 looks like this
JavaScript
1
5
1
ID earnings
2
101 20
3
103 40
4
105 60
5
My expected results is
JavaScript
1
7
1
ID name region earnings
2
101 Joseph A 120
3
102 Adam A 200
4
103 Clint C 190
5
104 Mark C 60
6
105 Michael A 60
7
How would I go about this please? My first thought was to iterate over every line but then I read that this is discouraged as it has poor performance.
Advertisement
Answer
You can use map
+ set_index
+ fillna
:
JavaScript
1
2
1
df1['earnings'] += df1['ID'].map(df2.set_index('ID')['earnings']).fillna(0).astype(int)
2
Output:
JavaScript
1
8
1
>>> df1
2
ID name region earnings
3
0 101 Joseph A 120
4
1 102 Adam A 200
5
2 103 Clint C 190
6
3 104 Mark C 60
7
4 105 Michael A 60
8