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 in Python by ana1504.k
• 7,890 points
214 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 by SDeb
• 13,190 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 in Python by Shabnam
• 920 points
48 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
• 56,940 points
1,167 views
0 votes
1 answer

How to concatenate Pandas dataframes?

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

answered May 14 in Python by Rasheed
45 views
+2 votes
2 answers

How can I replace values with 'none' in a dataframe using pandas

Actually in later versions of pandas this ...READ MORE

answered Aug 13, 2018 in Python by bug_seeker
• 15,360 points
7,727 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 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 348 views
0 votes
1 answer

df.mul vs df.rmul in Pandas

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

answered Jan 18 in Python by SDeb
• 13,190 points
163 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 in Python by SDeb
• 13,190 points
303 views