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

£可爱£侵袭症+ 提交于 2019-12-07 18:55:00

问题


I am very new to pandas and trying to use groupby. I have a df with multiple columns. I want to groupby a particular column and then sort each group based on a different column. I am getting the following error AttributeError: Cannot access callable attribute 'reset_index' of 'DataFrameGroupBy' objects, try using the 'apply' method.

Any help would be much appreciated!

Thanks!

col1 |  col2 | col3 | col4 | col5
=================================
A    |   A1   | A2   | A3   | DATE1
A    |   B1   | B2   | B3   | DATE2

I want to groupby col1 and then sort each group by col5 and then do reset_index to get all rows of the dataframe.

The following is the code I used. df.sort_values(['col5'],ascending=False).groupby('col1').reset_index()


回答1:


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()



回答2:


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?




回答3:


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']))



来源:https://stackoverflow.com/questions/50465023/attributeerror-cannot-access-callable-attribute-reset-index-of-dataframegrou

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