Combining DataFrame on Datetime index, summing values in other rows if same index

Viewed 277

I have two DataFrames with the same columns and I want to have them combined so the final dataframe only has a unique set of dates, but the Count column gets summed for any matching dates across the dataframes. Here is an example:

DataFrame1

     Date        Count
0    2020-01-01    5
1    2020-01-02    10

DataFrame2

     Date        Count
0    2020-01-01    10
1    2020-01-03    20

Result

     Date        Count
0    2020-01-01    15
1    2020-01-02    10
3    2020-01-03    20

What is the best way to do this?

1 Answers

Try, using groupby, and pd.concat:

res = (pd.concat([df1,df2],axis=0)).groupby('Date')['Count'].sum().reset_index()

Will get you:

         Date  Count
0  2020-01-01     15
1  2020-01-02     10
2  2020-01-03     20
Related