按 pandas 分组创建两个聚合列 [英] Create two aggregate columns by Group By Pandas

查看:96
本文介绍了按 pandas 分组创建两个聚合列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是DataFrames的新手,我想对多列进行分组,然后求和并保持最后一列的计数。例如

I'm new to DataFrames and I want to group multiple columns and then sum and keep a count on the last column. e.g.

s = pd.DataFrame(np.matrix([[1, 2,3,4], [3, 4,7,6],[3,4,5,6],[1,2,3,7]]), columns=['a', 'b', 'c', 'd'])

   a  b  c  d
0  1  2  3  4
1  3  4  7  6
2  3  4  5  6
3  1  2  3  7

我想分组到 a b c ,然后对 d 求和并计算组中的元素。
我可以用

I want to group on a, b and c but then sum on d and count the elements within the group. I can count by

s = s.groupby(by=["a", "b", "c"])["d"].count()

    a  b  c
    1  2  3    2
    3  4  5    1
          7    1

我可以总结为

s = s.groupby(by=["a", "b", "c"])["d"].sum()

a  b  c
1  2  3    11
3  4  5     6
      7     6

但是我想将其组合为结果数据框同时具有sum和count列。

However I want to combine it such that The resulting dataframe has both the sum and count columns.

    a  b  c   sum    count
    1  2  3    11     2
    3  4  5     6     1
          7     6     1


推荐答案

您可以使用 聚合 或更短版本的 agg

print (s.groupby(by=["a", "b", "c"])["d"].agg([sum, 'count']))
#print (s.groupby(by=["a", "b", "c"])["d"].aggregate([sum, 'count']))
       sum  count
a b c            
1 2 3   11      2
3 4 5    6      1
    7    6      1

熊猫文档

大小计数之间的差是:

大小 计算 NaN 值, count 可以

size counts NaN values, count does not.

如果需要计数 NaN 值,还:

print (s.groupby(by=["a", "b", "c"])["d"].agg([sum, 'size']))
       sum  size
a b c           
1 2 3   11     2
3 4 5    6     1
    7    6     1

这篇关于按 pandas 分组创建两个聚合列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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