JamesHudson81
JamesHudson81

Reputation: 2273

Add 2 dataframes with no exact index values

I have this df:

df1
          t0
ACER      50
BBV       20
ACC       75
IRAL      25
DECO      58

and on the other side :

df2
          t1
ACER      50
BBV       20
CEL        0
DIA       25

I am looking forward to add both dfs to obtain the following output:

df3
          t2
ACER      100
BBV       40
ACC       75
IRAL      25
DECO      58
DIA       25 
CEL        0  

Basically is the addition of the common index values in df1 and df2 and include those that didnt appeared in df1

I tried a

d1.add(df2) 

but Nan values arised, I also thought in merging dfs, substitute Nans by zeros and add columns , but I think maybe is lot of code to perform this.

Upvotes: 1

Views: 27

Answers (2)

cs95
cs95

Reputation: 402513

You were actually on the right track, you just needed fill_value=0:

df1.t0.add(df2.t1, fill_value=0).to_frame('t2')

         t2
ACC    75.0
ACER  100.0
BBV    40.0
CEL     0.0
DECO   58.0
DIA    25.0
IRAL   25.0

Note here that you'd have to add the Series objects together to prevent misalignment issues.

Upvotes: 1

Vaishali
Vaishali

Reputation: 38415

Use concat and sum

df3 = pd.concat([df1, df2], axis=1).sum(1)

ACC      75.0
ACER    100.0
BBV      40.0
CEL       0.0
DECO     58.0
DIA      25.0
IRAL     25.0

Upvotes: 2

Related Questions