Reputation: 641
I have multiple dataframes, all having the same shape but with different values. I need to merge the dataframes into one and add the values in the A, B, and C columns. Below is an example:
df1:
**Name,A,B,C**
Fred, 3, 4, 5
Tim, 1, 3, 0
Jake,4,2,10
df2:
**Name,A,B,C**
Fred, 1,0,4
Tim, 7,1,2
Jake,3,3,1
What I'm looking for is such:
df_merged:
**Name,A,B,C**
Fred,4,4,9
Tim,8,4,2
Jake,7,5,11
Keep in mind that I have multiple dataframes that need merged into 1 (6+).
Upvotes: 1
Views: 125
Reputation: 862481
Use concat
with aggregate sum
by GroupBy.sum
:
dfs = [df1, df2, df3, ...]
df = pd.concat(dfs).groupby('Name', as_index=False).sum()
dfs = [df1, df2]
df = pd.concat(dfs).groupby('Name', as_index=False).sum()
print (df)
Name A B C
0 Fred 4 4 9
1 Jake 7 5 11
2 Tim 8 4 2
Upvotes: 1