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

12,866

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'])
Share:
12,866
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    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'