可以说我有一个看起来像这样的表:
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
我想摆脱日期列,然后按公司AND区域进行汇总,以找到Count和Amount的总和。
预期产量:
Company Region Count Amount
AAA XXY 766 18630
BBB XYY 66 13150
我在这里查看了此帖子以及其他许多在线帖子,但似乎它们仅执行一种聚合操作(例如,我可以按多列进行聚合,但只能将一列输出作为总和或计数,而不是总和,计数)
重命名Pandas聚合中的结果列(“ FutureWarning:不建议将dict与重命名一起使用”)
有人可以帮忙吗?
我做了什么:
我在这里关注了这篇文章:
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)
我知道它现在可以工作,但是我想确保我的脚本也能以后工作。将来如何更新代码以使其兼容?
需要按单个非嵌套字典然后按rename
列进行聚合:
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
用另一种解决方案add_prefix
,而不是rename
:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句