Ahmed
Ahmed

Reputation: 278

Pandas Groupby of 2 dataframes

Is there a way to group 2 dataframes, so if i have

index      col1     col2    |  index     col1     col2 
0          AA       12      |  0          AA       12
1          AB       13      |  1          AB       13
2          AC       14      |  2          AD       15

(NOTE: "|" used to seperate the 2 df)

I would get

index    col1   col2
0        AA      24
1        AB      26
2        AC      14 
3        AD      15

Thanks!

Upvotes: 2

Views: 8939

Answers (2)

niraj
niraj

Reputation: 18208

import pandas as pd

df1 = pd.DataFrame({'col1':['AA','AB','AC'], 'col2':[12,13,14]})
df2 = pd.DataFrame({'col1':['AA','AB','AD'], 'col2':[12,13,15]})

Now, you can use concat to stack them and group them:

df = pd.concat( [df1, df2],axis=0,ignore_index=True)
df = df.groupby('col1').sum().reset_index()
print(df) 

Output:

   col1  col2
0   AA    24
1   AB    26
2   AC    14
3   AD    15

Upvotes: 4

Dmitriy Fialkovskiy
Dmitriy Fialkovskiy

Reputation: 3225

You can append DF2 to DF1 and then groupby:

import pandas as pd
df1=pd.DataFrame({'col1':['AA', 'AB','AC'], 'col2': [12,13,14]})
df2=pd.DataFrame({'col1':['AA', 'AB','AD'], 'col2': [12,13,15]})

df1=df1.append(df2)
df1.groupby('col1').sum()

Upvotes: 1

Related Questions