如何在Python中创建一个新的数据帧来分组求和和计数?

2024-05-17 16:38:09 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我试着做一些类似的事情:

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()

我还是不能让它为伯爵工作。我也在postGroup dataframe and get sum AND count?中尝试了这个答案,但是使用agg函数会让事情变得非常混乱,而且它会计算每一列

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


Tags: fromdfbycountgroup事情selectstudent
2条回答

您可以执行以下操作:

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

试试^{}

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

相关问题 更多 >