针对Pandas 0.22+进行了编辑,考虑了通过聚合弃用某个组中的字典。
我们建立了一个非常相似的字典,在其中我们使用字典的键来指定我们的函数,并使用字典本身来重命名列。
rnm_cols = dict(size='Size', sum='Sum', mean='Mean', std='Std')df.set_index(['Category', 'Item']).stack().groupby('Category') .agg(rnm_cols.keys()).rename(columns=rnm_cols) Size Sum Mean StdCategory Books 3 58 19.333333 2.081666Clothes 3 148 49.333333 4.041452Technology 6 1800 300.000000 70.710678选项1
使用agg
←链接到文档
agg_funcs = dict(Size='size', Sum='sum', Mean='mean', Std='std')df.set_index(['Category', 'Item']).stack().groupby(level=0).agg(agg_funcs) Std Sum Mean SizeCategory Books 2.081666 58 19.333333 3Clothes 4.041452 148 49.333333 3Technology 70.710678 1800 300.000000 6
选项2
更多,更少
使用describe
←链接到文档
df.set_index(['Category', 'Item']).stack().groupby(level=0).describe().unstack() count mean std min 25% 50% 75% maxCategory Books 3.0 19.333333 2.081666 17.0 18.5 20.0 20.5 21.0Clothes 3.0 49.333333 4.041452 45.0 47.5 50.0 51.5 53.0Technology 6.0 300.000000 70.710678 200.0 262.5 300.0 337.5 400.0



