Adding two pandas dataframes

0 votes
I have two dataframes, both indexed by timeseries. I need to add the elements together to form a new dataframe, but only if the index and column are the same. If the item does not exist in one of the  dataframes then it should be treated as a zero.

I've tried using .add but this sums regardless of index and column. Also tried a simple combined_data = dataframe1 + dataframe2 but this give a NaN if both dataframes don't have the element.

Can anyone help me with any suggestions?
Feb 12, 2019 in Python by ana1504.k
• 7,890 points
3,380 views

1 answer to this question.

0 votes
you can try the following:

x.add(y, fill_value=0)

import pandas as pd

df1 = pd.DataFrame([(1,2),(3,4),(5,6)], columns=['a','b'])
Out:
   a  b
0  1  2
1  3  4
2  5  6

df2 = pd.DataFrame([(100,200),(300,400),(500,600)], columns=['a','b'])
Out:
     a    b
0  100  200
1  300  400
2  500  600

df_add = df1.add(df2, fill_value=0)
Out:
     a    b
0  101  202
1  303  404
2  505  606
answered Feb 12, 2019 by SDeb
• 13,250 points

Related Questions In Python

0 votes
1 answer

How can I combine two dataframes in Python Pandas?

Hi, You can use the following methods to ...READ MORE

answered Jun 24, 2019 in Python by Shabnam
• 920 points
209 views
0 votes
1 answer

Pandas DataFrames in a loop, df.to_csv()

can you try something like this? not ...READ MORE

answered Sep 25, 2018 in Python by Priyaj
• 57,640 points
4,051 views
0 votes
1 answer

How to concatenate Pandas dataframes?

Suppose you have 3 dataframes named df1, ...READ MORE

answered May 14, 2019 in Python by Rasheed
198 views
0 votes
1 answer

How to merge two DataFrame in Pandas?

Hi@akhtar, You can use Pandas.merge() function to merge ...READ MORE

answered Jun 22 in Python by MD
• 55,740 points
82 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,352 views
0 votes
0 answers
0 votes
1 answer

df.mul vs df.rmul in Pandas

The documentation is not identical. As stated ...READ MORE

answered Jan 18, 2019 in Python by SDeb
• 13,250 points
338 views
0 votes
1 answer

Get business days between start and end date using pandas

You can use BDay() to get the ...READ MORE

answered Feb 15, 2019 in Python by SDeb
• 13,250 points
978 views