1

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

jpp
  • 159,742
  • 34
  • 281
  • 339
SFD
  • 565
  • 7
  • 18

2 Answers2

3

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
BENY
  • 317,841
  • 20
  • 164
  • 234
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
Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70