【问题标题】:Passing a function in pandas agg method of a groupby object在 groupby 对象的 pandas agg 方法中传递函数
【发布时间】:2020-12-05 12:30:12
【问题描述】:

这是在谷歌 colab 中

import pandas as pd
df = pd.DataFrame({'A': ['state1', 'state2', 'state1', 'state1', 'state2'], 
                   'B': [1, 2, 3, 4, 5], 
                   'C': [10, 11, 12, 13, 14]})
print(df)

      A     B    C
0   state1  1   10
1   state2  2   11
2   state1  3   12
3   state1  4   13
4   state2  5   14

这是数据框。如果我们将内置的 'max' 函数与 agg 函数一起使用,它就可以正常工作。

df.groupby('A', as_index=False)['C'].agg('max')

      A     C
0   state1  13
1   state2  14

但是如果我们使用lambda 函数会引发错误

df.groupby('A', as_index=False)['C'].agg(lambda x: x.max())

AttributeError: 'Series' object has no attribute 'columns'

为什么会引发错误?在agg方法中传递lambda函数和内置函数有什么区别?

即使对我来说,它也不能在 jupyter notebook 中工作

【问题讨论】:

  • 他们都在1.1.0为我工作
  • 他们都在0.25.1上为我工作
  • 编写一个完整的测试程序,在新的控制台上运行它,然后在此处发布程序和输出。
  • 我在 google colab 中运行它,但它在这里不起作用
  • 在 google colab 中检查您的 pandas 版本。使用此stackoverflow.com/a/53085629/6361531升级

标签: python pandas pandas-groupby aggregate


【解决方案1】:

这对我有用:

df.groupby('A', as_index=False)[['C']].agg(lambda x: x.max())

【讨论】:

    【解决方案2】:

    之前我第一次运行问题时,pandas 版本是 1.0.5。

    但之后我将版本更新到 1.1.0 并运行相同的东西,它工作正常。

    !pip install pandas==1.1.0
    import pandas as pd
    
    df = pd.DataFrame({'A': ['state1', 'state2', 'state1', 'state1', 'state2'], 
                       'B': [1, 2, 3, 4, 5], 
                       'C': [10, 11, 12, 13, 14]})
    
    print(df.groupby('A', as_index=False)['C'].agg(lambda x: x.max()))
    
           A     C
    0   state1  13
    1   state2  14
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 2021-07-14
      • 1970-01-01
      相关资源
      最近更新 更多