【问题标题】:pandas: how to group by multiple columns and perform different aggregations on multiple columns?pandas:如何按多列分组并对多列执行不同的聚合?
【发布时间】:2018-05-29 00:05:23
【问题描述】:

假设我有一张如下所示的表格:

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 列,然后按 Company AND region 聚合求 Count 和 sum of Amount 的平均值 .

预期输出:

Company      Region     Count         Amount
AAA          XXY        766           18630
BBB          XYY        66            13150

我在这里查看了这篇文章以及许多其他在线文章,但似乎它们只执行一种聚合操作(例如,我可以按多列聚合,但只能产生一列输出作为总和或计数, NOT sum AND 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)

我知道它现在可以工作,但我想确保我的脚本以后也可以工作。以后如何更新我的代码以兼容?

【问题讨论】:

  • 请同时发布您的预期输出。
  • @HaleemurAli 添加了!

标签: python pandas pandas-groupby


【解决方案1】:

需要通过单个非嵌套字典聚合,然后 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

【讨论】:

    【解决方案2】:
    df.groupby(['Region', 'Company']).agg({'Count': 'mean', 'Amount': 'sum'}).reset_index()
    

    输出:

      Region Company  Count  Amount
    0    XXY     AAA    766   18630
    1    XYY     BBB     66   13150
    

    【讨论】:

      【解决方案3】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-10
        • 1970-01-01
        • 1970-01-01
        • 2019-10-12
        • 2017-06-18
        • 2022-09-21
        • 2021-11-10
        • 2021-01-31
        相关资源
        最近更新 更多