groupby之后在同一列上应用多个操作

dai*_*yue 1 dataframe python-3.x pandas pandas-groupby

我有以下几点df

id    year_month    amount
10    201901        10
10    201901        20
10    201901        30
20    201902        40
20    201902        20
Run Code Online (Sandbox Code Playgroud)

我想groupby idyear-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')
Run Code Online (Sandbox Code Playgroud)

我想知道如何在一列中同时执行此操作;

id    year_month    amount    count
10    201901        60        3
20    201902        60        2
Run Code Online (Sandbox Code Playgroud)

Moh*_*ani 5

用途agg

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


                    amount
                   count    sum
id  year_month      
10  201901          3       60
20  201902          2       60
Run Code Online (Sandbox Code Playgroud)

如果要删除多索引,请使用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
Run Code Online (Sandbox Code Playgroud)