AttributeError: 无法访问“DataFrameGroupBy”对象的可调用属性“reset_index”,请尝试使用“apply”方法

Gin*_*ead 7 python-3.x pandas pandas-groupby

我对熊猫很陌生,并试图使用groupby. 我有一个多列的 df。

  • 我想对特定列进行分组,然后根据不同的列对每个组进行排序。
  • 我想col1分组,然后对每个组进行排序col5,然后执行reset_index以获取数据帧的所有行。
  • 我收到以下错误 AttributeError: Cannot access callable attribute 'reset_index' of 'DataFrameGroupBy' objects, try using the 'apply' method

我的输入数据框:

col1 |  col2 | col3 | col4 | col5
=================================
A    |   A1   | A2   | A3   | DATE1
A    |   B1   | B2   | B3   | DATE2
Run Code Online (Sandbox Code Playgroud)

我的代码:

df.sort_values(['col5'],ascending=False).groupby('col1').reset_index()
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 6

如果groupby需要一些聚合函数,例如mean, sum, max

df.sort_values(['col5'],ascending=False).groupby('col1').mean().reset_index()
Run Code Online (Sandbox Code Playgroud)

或者:

df.sort_values(['col5'],ascending=False).groupby('col1', as_index=False).mean()
Run Code Online (Sandbox Code Playgroud)