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

2024-09-28 22:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一张如下所示的桌子:

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

我想去掉日期列,然后按公司和地区进行汇总计算计数和金额总和的平均值。在

预期产量:

^{pr2}$

我在这里查看了这篇文章,以及许多其他的在线帖子,但似乎他们只是在执行一种聚合操作(例如,我可以按多个列进行聚合,但只能生成一个列作为sum或count的输出,而不是sum和count)

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)

我知道它现在起作用了,但我想确保我的脚本以后也能正常工作。我如何更新我的代码以便将来兼容?在


Tags: countwithamountdict帖子usingsumbbb
3条回答

{and non-Need dictionary}和非嵌套的^列:

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

另一个用^{}代替rename的解决方案:

^{pr2}$
df.groupby(['Region', 'Company']).agg({'Count': 'mean', 'Amount': 'sum'}).reset_index()

输出:

^{pr2}$

试试这个:

df.groupby(["Company","Region"]).agg({"Count":'mean',"Amount":'sum'})

相关问题 更多 >