Kalev Maricq
Kalev Maricq

Reputation: 617

Add two dataframes without sorting index

How can I add the values in 2 dataframes, by index value (0 for missing), without sorting the index.

import pandas as pd
df1=pd.DataFrame([1,2,3],['Yes','Maybe','No'],['Num'])
df2=pd.DataFrame([4,5],['Yes','No'],['Num'])
df1.add(df2,fill_value=0)
       Num
Maybe  2.0
No     8.0
Yes    5.0

I'd like to get:

Yes    5.0
Maybe  2.0
No     8.0

Concat adds extra rows instead of adding the values, and setting the index of one equal to the other before adding causes the values to be mislabeled. I'd like this to work for any index and be able to count on the same order. Is there a way to do that?

Upvotes: 0

Views: 101

Answers (1)

BENY
BENY

Reputation: 323326

This is due to index search when adding together, so we can fix reindex

out = df1.add(df2,fill_value=0).reindex(df1.index)
Out[281]: 
       Num
Yes    5.0
Maybe  2.0
No     8.0

Upvotes: 3

Related Questions