跳转至

🔥AI副业赚钱星球

点击下面图片查看

郭震AI

技巧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 0 1 10.0 1 3 8.0 2 1 6.0

对每个分组做聚合

对a列分组后,再对每个分组的b列按照均值,每个分组的c列求第一项,返回结果:

df.groupby(by=['a']).agg( {'b': 'mean', 'c': 'first'} )
b c a
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

大家在看

京ICP备20031037号-1 | AI之家 | AI资讯 | Python200 | 数据分析