AttributeError: Cannot access callable attribute 'reset_index' of 'DataFrameGroupBy' objects, try using the 'apply' method

扶醉桌前 提交于 2019-12-06 11:21:22

For groupby need some aggregation function(s), like mean, sum, max:

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

Or:

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

you can use

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)

Refer to this stackoverflow link for clear explanation with an example How to reset a DataFrame's indexes for all groups in one step?

You can try the below code, I had a similar issue.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!