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 nan
s. Is there a way to do this?
You can use
Series.add
with the argumentfill_value=0
: