Skip to content
Advertisement

Pandas merge 3 dataframes with same columns

I have 3 dataframes where I have one string column which I want to merge on and 2 similar columns which I want to add up

df1:

index user x y
 1    john 5 6
 2    pete 10 10 

df2:

index user x y
 1    john 1 1
 2    pete 2 2 
 3    nash 5 5

df3:

index user x y
 1    nash 6 7
 2    john 2 4 
 3    kyle 3 3

I want: df4:

index user x y
 1    john 8 11
 2    pete 12 12 
 3    nash 11 12
 4    kyle 3  3

Advertisement

Answer

try this, first pandas.concat then groupby

import pandas as pd

pd.concat([df1, df2, df3]).groupby(["user"], as_index=False)[['x', 'y']].sum()

   user   x   y
0  john   8  11
1  kyle   3   3
2  nash  11  12
3  pete  12  12
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement