python - 从 Pandas 聚合 ("FutureWarning: using a dict with renaming is deprecated"重命名结果列)

标签 python pandas aggregate rename

我正在尝试对 pandas 数据框进行一些聚合。这是一个示例代码:

import pandas as pd

df = pd.DataFrame({"User": ["user1", "user2", "user2", "user3", "user2", "user1"],
                  "Amount": [10.0, 5.0, 8.0, 10.5, 7.5, 8.0]})

df.groupby(["User"]).agg({"Amount": {"Sum": "sum", "Count": "count"}})

Out[1]: 
      Amount      
         Sum Count
User              
user1   18.0     2
user2   20.5     3
user3   10.5     1

这会产生以下警告:

FutureWarning: using a dict with renaming is deprecated and will be removed in a future version return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs)

我怎样才能避免这种情况?

最佳答案

使用 groupby apply 并返回一个 Series 来重命名列

使用 groupby apply 方法执行聚合

  • 重命名列
  • 名称中允许有空格
  • 允许您以您选择的任何方式对返回的列进行排序
  • 允许列之间的交互
  • 返回单级索引而不是 MultiIndex

为此:

  • 创建一个您传递给 apply
  • 的自定义函数
  • 此自定义函数作为 DataFrame 传递给每个组
  • 返回一个系列
  • Series 的索引将是新列

创建虚假数据

df = pd.DataFrame({"User": ["user1", "user2", "user2", "user3", "user2", "user1", "user3"],
                  "Amount": [10.0, 5.0, 8.0, 10.5, 7.5, 8.0, 9],
                  'Score': [9, 1, 8, 7, 7, 6, 9]})

enter image description here

创建返回系列的自定义函数
my_agg 里面的变量x 是一个DataFrame

def my_agg(x):
    names = {
        'Amount mean': x['Amount'].mean(),
        'Amount std':  x['Amount'].std(),
        'Amount range': x['Amount'].max() - x['Amount'].min(),
        'Score Max':  x['Score'].max(),
        'Score Sum': x['Score'].sum(),
        'Amount Score Sum': (x['Amount'] * x['Score']).sum()}

    return pd.Series(names, index=['Amount range', 'Amount std', 'Amount mean',
                                   'Score Sum', 'Score Max', 'Amount Score Sum'])

将此自定义函数传递给 groupby apply 方法

df.groupby('User').apply(my_agg)

enter image description here

最大的缺点是这个函数将比 cythonized aggregationsagg 慢得多。

使用带有 groupby agg 方法的字典

由于字典的复杂性和含糊不清的性质,已删除使用字典的字典。有一个ongoing discussion关于 future 如何在 github 上改进这个功能在这里,您可以在 groupby 调用后直接访问聚合列。只需传递您希望应用的所有聚合函数的列表。

df.groupby('User')['Amount'].agg(['sum', 'count'])

输出

       sum  count
User              
user1  18.0      2
user2  20.5      3
user3  10.5      1

仍然可以使用字典来显式表示不同列的不同聚合,就像这里如果有另一个名为 Other 的数字列。

df = pd.DataFrame({"User": ["user1", "user2", "user2", "user3", "user2", "user1"],
              "Amount": [10.0, 5.0, 8.0, 10.5, 7.5, 8.0],
              'Other': [1,2,3,4,5,6]})

df.groupby('User').agg({'Amount' : ['sum', 'count'], 'Other':['max', 'std']})

输出

      Amount       Other          
         sum count   max       std
User                              
user1   18.0     2     6  3.535534
user2   20.5     3     5  1.527525
user3   10.5     1     4       NaN

关于python - 从 Pandas 聚合 ("FutureWarning: using a dict with renaming is deprecated"重命名结果列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44635626/

相关文章:

Python Unittest 抛出未捕获的 TypeError : __init__() takes 1 positional argument but 2 were given

python - 在 matplotlib 中分页/滚动二维热图集

python - Reactor.run 卡住循环

python pandas read_csv如何加快处理时间戳

SQL关于计数的问题

sql - 如何聚合描述列?

聚合的 MySQL 查询

python - 将文本输入保存到 kivy 应用程序中的变量

python - Pandas MultiIndex 与 Panel

python - Label Encoding() 与 One Hot Encoding() (sklearn,pandas) 建议