Join 2 DataFrames on an index without introducing nans on missing indices

55 Views Asked by At

I have 2 DataFrames:

df1 = pandas.DataFrame([[1,2,3],[4,5,6],[7,8,9]], columns=['a','b','c'])
df2 = df1*2
df2.index = [1,2,3]

>>> df1
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

>>> df2
    a   b   c
1   2   4   6
2   8  10  12
3  14  16  18

Say I want to add the a column from df2 to df1 based on index:

df1['a'] += df2['a']
>>> df1
    a  b  c
0 NaN  2  3
1   6  5  6
2  15  8  9

This works fine when the index is present in both frames, but I would like to just add zero in the case where an index is missing, rather than introduce nans. Is there a way to do this?

1

There are 1 best solutions below

0
On BEST ANSWER

You can use Series.add with the argument fill_value=0:

>>> df1['a'] = df1['a'].add(df2['a'], fill_value=0)

>>> df1
    a  b  c
0   1  2  3
1   6  5  6
2  15  8  9