pandas 如何合并两个数据框并对列的值求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49111859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:16:20  来源:igfitidea点击:

how to merge two dataframes and sum the values of columns

pythonpandasdataframedata-analysis

提问by chandru

I have two dataframes

我有两个数据框

df1
Name class value
Sri   1     5
Ram   2     8
viv   3     4

df2
Name class value
Sri   1     5
viv   4     4

My desired output is,

我想要的输出是,

df,

Name class value
Sri   2     10
Ram   2     8
viv   7     8

Please help, thanks in advance!

请帮忙,先谢谢了!

采纳答案by jezrael

I think need set_indexfor both DataFrames, addand last reset_index:

我认为s和 lastset_index都需要:DataFrameaddreset_index

df = df1.set_index('Name').add(df2.set_index('Name'), fill_value=0).reset_index()
print (df)
  Name  class  value
0  Ram    2.0    8.0
1  Sri    2.0   10.0
2  viv    7.0    8.0

If values in Nameare not unique use groupbyand aggregate sum:

如果中的值Name不是唯一的 usegroupby和aggregate sum

df = df1.groupby('Name').sum().add(df2.groupby('Name').sum(), fill_value=0).reset_index()

回答by jpp

pd.concat+ groupby+ sum

pd.concat+ groupby+sum

You can concatenate your individual dataframes and then group by your key column:

您可以连接您的个人数据框,然后按您的关键列分组:

df = pd.concat([df1, df2])\
       .groupby('Name')['class', 'value']\
       .sum().reset_index()

print(df)

  Name  class  value
0  Ram      2      8
1  Sri      2     10
2  viv      7      8