简体   繁体   中英

Merge sum rows with multiindex with Pandas

Is it possible to merge and sum rows that appear in both dataframes with multiindex, while adding the ones that are unique to each dataframe.

df1

       Amount1 Amount2 Amount3
A R10  1        1          20
  R3   0        0          20
  X2   1        0          20
B XS1  1        5          10 
  LM2  1        1          10
C RR1  2        1          30

df2

       Amount1 Amount2 Amount3
A R10  1        1          20
  X2   1        0          20
B XS1  1        5          10 
  XF2  1        1          10
C RR1  2        1          30

Final result:

       Amount1 Amount2 Amount3
A R10  2        2          40
  R3   0        0          20
  X2   2        0          40
B XS1  2        10         20 
  LM2  1        1          10
  XF2  1        1          10
C RR1  4        2          60

Try:

df1.add(df2, fill_value=0)

Output:

       Amount1  Amount2  Amount3
A R10      2.0      2.0     40.0
  R3       0.0      0.0     20.0
  X2       2.0      0.0     40.0
B LM2      1.0      1.0     10.0
  XF2      1.0      1.0     10.0
  XS1      2.0     10.0     20.0
C RR1      4.0      2.0     60.0

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