ASDu
ASDu

Reputation: 89

Sum to dataframes based on row and column

Given to Dataframes df_1

Code | Jan | Feb | Mar
a    | 1   | 2   | 1
b    | 3   | 4   | 3

and df_2

Code | Jan | Feb | Mar
a    | 1   | 1   | 2
c    | 7   | 0   | 0

I would like to sum these to tables based on the row and colum. So my result dataframe shoul look like this:

Code | Jan | Feb | Mar
a    | 2   | 3   | 3
b    | 3   | 4   | 3
c    | 7   | 0   | 0

Is there an easy way to do this? I can to this using a lot of for loops and if statements but this is very slow for large datasets.

Upvotes: 0

Views: 34

Answers (1)

jezrael
jezrael

Reputation: 862511

Use concat and aggregate sum:

df = pd.concat([df_1, df_2]).groupby('Code', as_index=False).sum()
print (df)
  Code  Jan  Feb  Mar
0    a    2    3    3
1    b    3    4    3
2    c    7    0    0

Upvotes: 3

Related Questions