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

如何在Python中创建一个新的数据帧来分组求和和计数?,python,pandas,group-by,Python,Pandas,Group By,所以,我试着做一些类似的事情: 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

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

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()
我还是不能让它为伯爵工作。我在帖子中也尝试过这个答案,但是使用agg函数会让事情变得非常混乱,而且它会计算每一列

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

您可以执行联接:

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”消失了是的,我试图用一些任意的字符串填充Na,但没有修复。使用这个代码我会失去一些安德鲁斯和比利。不知道为什么,还有别的办法吗?问题是,我实际上并不是只有d和e要求和,它至少有100列要总结。你可以用dict理解为你想求和的列建立一个namedag字典
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