Mamath
Mamath

Reputation: 317

Pandas sum DataFrame into a larger DataFrame already containing same index with same columns name

I just want to know if someone have a more elegant solution for the problem below:

I have two Pandas DataFrame:

import pandas as pd
df1 = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list('ABC'))
df2 = pd.DataFrame([[10, 20, 30], [40, 50, 60]], columns=list('ABC'))

    A   B   C
0   1   2   3 
1   4   5   6
2   7   8   9


    A   B   C
0   10  20  30
1   40  50  60

And I just want to sum the df2 into the df1 based on index with the same columns:

    A   B   C
0   11  22  33
1   44  55  66
2   7   8   9

My solution so far:

df_merge = df1.merge(df2, how='inner', left_index=True, right_index=True, suffixes=['_l', '_r'])
for elt in list('ABC'):
    df_merge[elt] = df_merge[elt + '_l'] + df_merge[elt + '_r']
    df_merge.drop([elt + '_l', elt + '_r'], axis=1, inplace=True)
df1.update(df_merge)

Thanks for your help!

Upvotes: 3

Views: 127

Answers (2)

Alexander
Alexander

Reputation: 109626

Using df.add(df2) is equivalent to df1 + df2, but allows you to fill in a value where the indices and columns do not align.

>>> df1.add(df2, fill_value=0)
    A   B   C
0  11  22  33
1  44  55  66
2   7   8   9

Upvotes: 4

Dennis Golomazov
Dennis Golomazov

Reputation: 17349

You can use concat and groupby:

pd.concat((df1, df2)).groupby(level=0).sum()

    A   B   C
0  11  22  33
1  44  55  66
2   7   8   9

Upvotes: 1

Related Questions