python – pandas:如何按多列分组并在多列上执行不同的聚合?
发布时间:2020-12-20 11:05:05 所属栏目:Python 来源:网络整理
导读:可以说我有一个看起来像这样的表: Company Region Date Count AmountAAA XXY 3-4-2018 766 8000AAA XXY 3-14-2018 766 8600AAA XXY 3-24-2018 766 2030BBB XYY 2-4-2018 66 3400BBB XYY 3-18-2018 66 8370BBB XYY 4-6-2018 66 1380 我想摆脱Date列,然后按公
可以说我有一个看起来像这样的表:
Company Region Date Count Amount AAA XXY 3-4-2018 766 8000 AAA XXY 3-14-2018 766 8600 AAA XXY 3-24-2018 766 2030 BBB XYY 2-4-2018 66 3400 BBB XYY 3-18-2018 66 8370 BBB XYY 4-6-2018 66 1380 我想摆脱Date列,然后按公司和地区汇总,找到Count的平均值和Amount的总和. 预期产量: Company Region Count Amount AAA XXY 766 18630 BBB XYY 66 13150 我在这里查看了这篇文章,还有很多其他在线帖子,但看起来他们只是执行一种聚合操作(例如,我可以通过多列聚合,但只能产生一个列输出作为总和OR计数,而不是和和计数) Rename result columns from Pandas aggregation (“FutureWarning: using a dict with renaming is deprecated”) 有人可以帮忙吗? 我做了什么: 我在这里关注这篇文章: https://www.shanelynn.ie/summarising-aggregation-and-grouping-data-in-python-pandas/ 但是,当我尝试使用本文中提供的方法(在文章末尾)时,通过使用字典: aggregation = { 'Count': { 'Total Count': 'mean' },'Amount': { 'Total Amount': 'sum' } } 我会收到这个警告: FutureWarning: using a dict with renaming is deprecated and will be removed in a future version return super(DataFrameGroupBy,self).aggregate(arg,*args,**kwargs) 我知道它现在有效但我想确保我的脚本也能在以后工作.如何更新我的代码以便将来兼容? 解决方法
需要通过单个非嵌套字典进行聚合,然后重命名列:
aggregation = {'Count': 'mean','Amount': 'sum'} cols_d = {'Count': 'Total Count','Amount': 'Total Amount'} df = df.groupby(['Company','Region'],as_index=False).agg(aggregation).rename(columns=cols_d) print (df) Company Region Total Count Total Amount 0 AAA XXY 766 18630 1 BBB XYY 66 13150 使用 aggregation = {'Count': 'mean','Amount': 'sum'} df = df.groupby(['Company','Region']).agg(aggregation).add_prefix('Total ').reset_index() print (df) Company Region Total Count Total Amount 0 AAA XXY 766 18630 1 BBB XYY 66 13150 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |