【问题标题】:AttributeError: Cannot access callable attribute 'reset_index' of 'DataFrameGroupBy' objects, try using the 'apply' methodAttributeError:无法访问“DataFrameGroupBy”对象的可调用属性“reset_index”,请尝试使用“应用”方法
【发布时间】:2018-11-01 01:33:45
【问题描述】:

我对 pandas 很陌生,正在尝试使用 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

我的代码:

df.sort_values(['col5'],ascending=False).groupby('col1').reset_index()

【问题讨论】:

  • 你的groupby 代码是什么?
  • 提供样本输出
  • @jezrael:我已经提供了示例代码。

标签: python-3.x pandas pandas-groupby


【解决方案1】:

你可以试试下面的代码,我也遇到过类似的问题。

grouped=data.groupby(['Colname'])
grouped.apply(lambda _df: _df.sort_values(by=['col_to_be_sorted']))

【讨论】:

    【解决方案2】:

    你可以使用

    grouped = df.sort_values(['col5'],ascending=False).groupby('col1',as_index = False).apply(lambda x: x.reset_index(drop = True))
    grouped.reset_index().drop(['level_0','level_1'],axis = 1)
    

    请参阅此 stackoverflow 链接以通过示例进行清晰说明 How to reset a DataFrame's indexes for all groups in one step?

    【讨论】:

      【解决方案3】:

      对于groupby,需要一些聚合函数,例如meansummax

      df.sort_values(['col5'],ascending=False).groupby('col1').mean().reset_index()
      

      或者:

      df.sort_values(['col5'],ascending=False).groupby('col1', as_index=False).mean()
      

      【讨论】:

      • 这将我的数据框的形状从 (124,14) 减少到 (9,6)。我想要所有 124 行。你能帮忙吗?
      • 抱歉,根据 OP 发布的代码,这不是答案。他们正在做一个排序,而不是汇总功能。他们想要所有的 df 行。
      猜你喜欢
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      相关资源
      最近更新 更多