简体   繁体   中英

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

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

You can first concatenate using pd.concat , then use df.groupby :

In [390]: pd.concat([df, df2]).groupby('country', as_index=False).sum()
Out[390]: 
  country  value
0      FF      6
1      MM      1
2      aa      3
3      bb      1
4      cc     13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM