首页 > 解决方案 > 在 groupby 之后对同一列应用多个操作

问题描述

我有以下df

id    year_month    amount
10    201901        10
10    201901        20
10    201901        30
20    201902        40
20    201902        20

我想groupby id然后year-month得到组大小和总和amount

df.groupby(['id', 'year_month'], as_index=False)['amount'].sum()

df.groupby(['id', 'year_month'], as_index=False).size().reset_index(name='count')

我想知道如何在一行中同时进行;

id    year_month    amount    count
10    201901        60        3
20    201902        60        2

标签: python-3.xpandasdataframepandas-groupby

解决方案


使用agg

df.groupby(['id', 'year_month']).agg({'amount': ['count', 'sum']})


                    amount
                   count    sum
id  year_month      
10  201901          3       60
20  201902          2       60

如果要删除多索引,请使用MultiIndex.droplevel

s = df.groupby(['id', 'year_month']).agg({'amount': ['count', 'sum']}).rename(columns ={'sum': 'amount'})
s.columns = s.columns.droplevel(level=0)
s.reset_index()

    id  year_month  count   amount
0   10  201901        3      60
1   20  201902        2      60

推荐阅读