pandas 分组依据并求和两列 [英] Pandas group by and sum two columns

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

问题描述

初学者问题.看来这应该是一个简单的操作,但是我无法通过阅读文档来弄清楚.

Beginner question. This seems like it should be a straightforward operation, but I can't figure it out from reading the docs.

我有一个具有以下结构的df:

I have a df with this structure:

|integer_id|int_field_1|int_field_2|

integer_id列是非唯一的,因此我想按integer_id对df进行分组,并对两个字段求和.

The integer_id column is non-unique, so I'd like to group the df by integer_id and sum the two fields.

等效的SQL是:

SELECT integer_id, SUM(int_field_1), SUM(int_field_2) FROM tbl
GROUP BY integer_id

关于最简单的方法有什么建议吗?

Any suggestions on the simplest way to do this?

包括输入/​​输出

Input:  
integer_id  int_field_1 int_field_2   
2656        36          36  
2656        36          36  
9702        2           2  
9702        1           1  

使用df.groupby('integer_id').sum()的输出:

Ouput using df.groupby('integer_id').sum():

integer_id  int_field_1 int_field_2  
2656        72          72  
9702        3           3  

推荐答案

您只需要在groupby对象上调用sum:

You just need to call sum on a groupby object:

df.groupby('integer_id').sum()

有关更多示例,请参见文档

See the docs for further examples

这篇关于 pandas 分组依据并求和两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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