Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects, try using the 'apply' method'

I am trying to sort numbers column in dataframe but getting this error 'id' column has count of id's at specific stations. e.g. 2272, 2202, 1855, etc.

df.sort_values(by=['id'])

However, I am getting this error:

'Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects, try using the 'apply' method'

like image 896
Kalsoom Malik Avatar asked Jun 17 '26 17:06

Kalsoom Malik


1 Answers

You're trying to call a DataFrame method from GroupBy object. If your goal is to sort within each group, you can simply pass multiple keys in by:

with df as a dataframe and not a groupby object ...

df.sort_values(by=['groupby_key1', 'groupby_key2', '...', 'id'])

If you want to sort within the group by, do as the error message suggests and use apply (with df as a dataframe and not a groupby object):

gb = df.groupby(['gropuby_key1', 'groupby_key2', '...'])
gb.apply(lambda _df: _df.sort_values(by=['id'])
like image 54
Thtu Avatar answered Jun 19 '26 05:06

Thtu