根据另一列中的项目对pandas列中的值求和 [英] Sum the values in a pandas column based on the items in another column

查看:60
本文介绍了根据另一列中的项目对pandas列中的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何基于熊猫数据框中一"列中的项求和第二"列中的值:

how can I sum the values in column 'two' based on the items in column 'one' in pandas dataframe:

df = pd.DataFrame({'One': ['A', 'B', 'A', 'B'], 'Two': [1, 5, 3, 4]})
out[1]:
        One      Two
    0   A         1          
    1   B         5         
    2   A         3               
    3   B         4

预期输出应为:

A    4
B    9

推荐答案

您需要group by第一列,sum在第二列.

You need to group by the first column and sum on the second.

df.groupby('One', as_index=False).sum()

  One  Two
0   A    4
1   B    9

这篇关于根据另一列中的项目对pandas列中的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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