栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python Pandas Groupby聚合在多个列上,然后旋转

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python Pandas Groupby聚合在多个列上,然后旋转

针对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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659584.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号