title: 技巧23: 对每个分组做聚合 date: 2024-11-28
技巧23: 对每个分组做聚合
输入
import pandas as pd
df = pd.DataFrame({"a":[1,3,1], "b":[10.0,8.0,6.0], "c":['qaz', 'wsx', 'edc']})
df
对每个分组做聚合
对a列分组后,再对每个分组的b列按照均值,每个分组的c列求第一项,返回结果:
df.groupby(by=['a']).agg( {'b': 'mean', 'c': 'first'} )
1 8.0 qaz 3 8.0 wsx
其中聚合agg
参数还支持:
'last', 'first',
'head', 'tail', 'median',
'mean', 'sum', 'min', 'max',
'cumcount', 'ngroup',
'resample',
'rank', 'quantile',
'fillna',
'mad',
'any', 'all',
'take',
'idxmax', 'idxmin',
'shift', 'tshift',
'ffill', 'bfill',
'pct_change', 'skew',
'corr', 'cov', 'diff',
参考链接: https://github.com/pandas-dev/pandas/blob/v0.23.1/pandas/core/groupby/groupby.py#L4652-L4658