pandas groupby sort descending order

前端 未结 6 1466
离开以前
离开以前 2020-12-28 13:02

pandas groupby will by default sort. But I\'d like to change the sort order. How can I do this?

I\'m guessing that I can\'t apply a sort method to the returned gro

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-28 13:25

    Similar to one of the answers above, but try adding .sort_values() to your .groupby() will allow you to change the sort order. If you need to sort on a single column, it would look like this:

    df.groupby('group')['id'].count().sort_values(ascending=False)
    

    ascending=False will sort from high to low, the default is to sort from low to high.

    *Careful with some of these aggregations. For example .size() and .count() return different values since .size() counts NaNs.

    What is the difference between size and count in pandas?

提交回复
热议问题