与groupby的 pandas 数据帧总和 [英] pandas dataframe sum with groupby
本文介绍了与groupby的 pandas 数据帧总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫数据框,结构上看起来像这样:
I have a pandas dataframe that structurally looks like this:
[
['x', '1', '-7']
['x', '2', '-2']
['y', '3', '-1']
['y', '4', '-3']
]
我必须对第一列(值x
和y
s)进行分组,并为每个x
和y
找到第二列和第三列的总和,如下所示:
I have to groupby the first column (with values x
and y
s) and find the sum for the second and third column for each x
and y
like this:
[
['x', 3, -9]
['y', 7, -4]
]
如何使用熊猫来做到这一点?
How can I do this using pandas?
推荐答案
设置
我已将您的字符串数字转换为实际数字
setup
I converted your string numbers to actual numbers
df = pd.DataFrame(
[
['x', '1', '-7'],
['x', '2', '-2'],
['y', '3', '-1'],
['y', '4', '-3']
]
)
df[1] = pd.to_numeric(df[1])
df[2] = pd.to_numeric(df[2])
解决方案
solution
df.groupby(0).sum()
这篇关于与groupby的 pandas 数据帧总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文