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
• 5,910 points
25 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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
• 9,380 points

Related Questions In Python

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,100 points
382 views
0 votes
1 answer

How to concatenate Pandas dataframes?

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

answered 6 days ago in Python by Rasheed
6 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
• 14,960 points
2,376 views
0 votes
1 answer

How can I compare the content of two files in Python?

Assuming that your file unique.txt just contains ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,710 points
33 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 920 points
19 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
• 9,380 points
56 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
• 9,380 points
98 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.