Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum the columns of two dataframes of different length

I have two dataframes:

df1

    country  value
0      aa      1
1      bb      1
2      cc      5

df2

     country  value
0      cc      8
1      aa      2
2      MM      1
3      FF      6

How get I can this dataframe (df1 + df2) as follows:

    country  value
0      aa      3
1      bb      1
2      MM      1
3      cc      13
4      FF      6
like image 635
xingyuan jiang Avatar asked Dec 24 '22 15:12

xingyuan jiang


1 Answers

Use set_index and add with fill_value=0:

df1.set_index('country').add(df2.set_index('country'),fill_value=0).reset_index()

Output:

  country  value
0      FF    6.0
1      MM    1.0
2      aa    3.0
3      bb    1.0
4      cc   13.0
like image 159
Scott Boston Avatar answered Jan 08 '23 20:01

Scott Boston