python-3.x - AttributeError:无法访问“DataFrameGroupBy”对象的可调用属性“reset_index”,请尝试使用“应用”方法
问题描述
我对 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
需要一些聚合函数,如mean
, sum
, max
:
df.sort_values(['col5'],ascending=False).groupby('col1').mean().reset_index()
或者:
df.sort_values(['col5'],ascending=False).groupby('col1', as_index=False).mean()
推荐阅读
- javascript - 动态重组一个对象数组,每个对象包含两个属性值对
- postgresql - PostgreSQL。两列的唯一性
- c++ - 尝试使用虚拟零件手动创建 unique_ptr 类实例
- virtual-machine - 未使用 Azure 站点恢复故障转移复制 NSG 规则
- c# - 有没有办法统一更改脚本中 CharacterJoint 组件的值(例如 hightwistlimit)?
- pine-script - 在 TradingView Pine Script 上获取特定柱的日期
- jenkins - Jenkins UI - 缺少“环境变量”按钮
- swift - ld:警告:找不到或使用自动链接库“swiftCore”
- typescript - 如何在不共享 Express Requests 的情况下创建 Typescript Map
- mongodb - MongoError:此 MongoDB 部署不支持可重试写入。请将 retryWrites=false 添加到您的连接字符串