DataFrameGroupBy对象不能使用sort_values()的解决办法

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

 

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值