Python 在使用 sum() 和 groupby 时保留其他列 [英] Python Keep other columns when using sum() with groupby

查看:470
本文介绍了Python 在使用 sum() 和 groupby 时保留其他列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有一个熊猫数据框:

I have a pandas dataframe below:

    df

    name    value1    value2  otherstuff1 otherstuff2 
0   Jack       1         1       1.19        2.39     
1   Jack       1         2       1.19        2.39
2   Luke       0         1       1.08        1.08  
3   Mark       0         1       3.45        3.45
4   Luke       1         0       1.08        1.08

对于otherstuff1 和otherstuff2,相同的名称"将具有相同的值.

Same "name" will have the same value for otherstuff1 and otherstuff2.

我正在尝试按列 'name' 和 sum 列 'value1' 和 sum 列 'value2' 进行分组(不是将 value1 与 value2 相加!!!而是在每列中分别对它们求和)

I'm trying to groupby by column 'name' and sum column 'value1' and sum column 'value2' (Not sum value1 with value2!!! But sum them individually in each column)

期望得到以下结果:

    newdf

    name    value1    value2  otherstuff1 otherstuff2 
0   Jack       2         3       1.19        2.39     
1   Luke       1         1       1.08        1.08  
2   Mark       0         1       3.45        3.45

我试过了

newdf = df.groupby(['name'], as_index = False).sum()

按名称分组并对 value1 和 value2 列正确求和,但最终删除了 otherstuff1 和 otherstuff2 列.

which groupsby name and sums up both value1 and value2 columns correctly but end up dropping column otherstuff1 and otherstuff2.

请帮忙.非常感谢你们!

Please help. Thank you guys so much!

推荐答案

类似的东西?(假设你有同名的otherstuff1和otherstuff2)

Something like ?(Assuming you have same otherstuff1 and otherstuff2 under the same name )

df.groupby(['name','otherstuff1','otherstuff2'],as_index=False).sum()
Out[121]: 
   name  otherstuff1  otherstuff2  value1  value2
0  Jack         1.19         2.39       2       3
1  Luke         1.08         1.08       1       1
2  Mark         3.45         3.45       0       1

这篇关于Python 在使用 sum() 和 groupby 时保留其他列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆