简体   繁体   中英

Panda, summing multiple DataFrames with different columns

I have the following DataFrames:

A =  
  0 1 2 
0 1 1 1
1 1 1 1
2 1 1 1

B = 
  0 5
0 1 1
5 1 1

I want to 'join' these two frames such that:

A + B =
   0 1 2 5
 0 2 1 1 1
 1 1 1 1 0
 2 1 1 1 0
 5 1 0 0 1  

where A+B is a new dataframe

Using add

df1.add(df2,fill_value=0).fillna(0)
Out[217]: 
     0    1    2    5
0  2.0  1.0  1.0  1.0
1  1.0  1.0  1.0  0.0
2  1.0  1.0  1.0  0.0
5  1.0  0.0  0.0  1.0

If you need int

df1.add(df2,fill_value=0).fillna(0).astype(int)
Out[242]: 
   0  1  2  5
0  2  1  1  1
1  1  1  1  0
2  1  1  1  0
5  1  0  0  1
import numpy as np
import pandas as pd

A = pd.DataFrame(np.ones(9).reshape(3, 3))
B = pd.DataFrame(np.ones(4).reshape(2, 2), columns=[0, 5], index=[0, 5])

A.add(B, fill_value=0).fillna(0)

[Out]
    0       1       2       5
0   2.0     1.0     1.0     1.0
1   1.0     1.0     1.0     0.0
2   1.0     1.0     1.0     0.0
5   1.0     0.0     0.0     1.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