pandas groupby sort descending order

前端 未结 6 1449
离开以前
离开以前 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:14

    As of Pandas 0.18 one way to do this is to use the sort_index method of the grouped data.

    Here's an example:

    np.random.seed(1)
    n=10
    df = pd.DataFrame({'mygroups' : np.random.choice(['dogs','cats','cows','chickens'], size=n), 
                       'data' : np.random.randint(1000, size=n)})
    
    grouped = df.groupby('mygroups', sort=False).sum()
    grouped.sort_index(ascending=False)
    print grouped
    
    data
    mygroups      
    dogs      1831
    chickens  1446
    cats       933
    

    As you can see, the groupby column is sorted descending now, indstead of the default which is ascending.

提交回复
热议问题