简体   繁体   中英

Merging multiple dataframes and summing values

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+).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM