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'
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With