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,910 points
9,735 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,300 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 25, 2019 in Python by Shabnam
• 930 points
1,296 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
• 58,020 points
10,425 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
785 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 23, 2020 in Python by MD
• 95,460 points
1,054 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,464 views
0 votes
1 answer
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,300 points
1,215 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,300 points
2,077 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP