【问题标题】:How can I group sum and count in Python creating a new dataframe?如何在 Python 中对 sum 和 count 进行分组以创建新的数据框?
【发布时间】:2020-08-15 02:42:09
【问题描述】:

所以,我正在尝试做类似的事情:

select a, b, c, sum(d), sum(e), count(*)
from df 
group by 1,2,3

换句话说,我有这个:

a        b        c    d    e
Billy    Profesor 1    10   5
Billy    Profesor 1    17   3
Andrew   Student  8    2    7

我希望输出是:

a        b        c    d    e    count
Billy    Profesor 1    27   8    2
Andrew   Student  8    2    7    1

我试过这个,它部分工作:

df.groupby(['a','b','c']).sum().reset_index()

我仍然无法让它为计数工作。我也在帖子Group dataframe and get sum AND count? 中尝试了答案,但是使用 agg 函数会使事情变得非常混乱,而且它会计算每一列。

更新:我更改了 c 列,因为我有一个要分组的数字列,但没有求和。

【问题讨论】:

    标签: python pandas group-by


    【解决方案1】:

    你可以加入:

    groups=df.groupby(['a','b','c'])
    groups.sum().join(groups.size().to_frame('count')).reset_index()
    

    输出:

            a         b   c   d  e  count
    0  Andrew   Student  CA   2  7      1
    1   Billy  Profesor  NY  27  8      2
    

    【讨论】:

    • 不知道发生了什么,但对我来说,输出中的几个 'Andrew's 消失了
    • 是的,我尝试用一​​些任意字符串填充na,但它没有修复。使用此代码,我失去了一些 Andrews 和 Billies。不知道为什么。
    【解决方案2】:

    试试NamedAgg

    df_final = df.groupby(['a','b','c'], sort=False).agg(d=('d', 'sum'), 
                                                         e=('e', 'sum'), 
                                                         count=('e', 'count')).reset_index()
    
    Out[12]:
            a         b   c   d  e  count
    0   Billy  Profesor  NY  27  8      2
    1  Andrew   Student  CA   2  7      1
    

    【讨论】:

    • 还有其他方法吗?问题是我实际上并没有只有 d 和 e 可以总结,至少要总结 100 列
    • 你可以为NamedAgg 为你想要使用dict理解求和的列构建一个字典
    猜你喜欢
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 2020-06-24
    • 1970-01-01
    • 2022-09-23
    • 2022-01-07
    相关资源
    最近更新 更多