python – pandas:如何按多列分组并在多列上执行不同的聚合?

可以说我有一个看起来像这样的表:

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

使用add_prefix重命名的另一个解决方案:

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
点赞