Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas value_counts: sort by value, then alphabetically?

Tags:

python

pandas

I have the following data frame:

df = pd.DataFrame({
    'fruit':
       ['peaches']*5 + ['apples']*5 + ['bananas']*3 + 
       ['nectarines']*3 + ['carrots']*3 + ['apricots'] 
})

And I would like to get output sorted first by the value count, then alphabetically by the name of the fruit:

apples        5
peaches       5
bananas       3
carrots       3
nectarines    3
apricots      1

I found this answer, but it looks out of date.

like image 219
Richard Avatar asked Dec 05 '22 10:12

Richard


1 Answers

Seems like just using value_counts will yield the result

df.fruit.value_counts()
Out[818]: 
apples        5
peaches       5
bananas       3
carrots       3
nectarines    3
apricots      1
Name: fruit, dtype: int64

Update

df.fruit.value_counts().sort_index(ascending=False).sort_values(ascending=False)    

apples        5
peaches       5
bananas       3
carrots       3
nectarines    3
apricots      1
Name: fruit, dtype: int64
like image 145
BENY Avatar answered Jan 01 '23 07:01

BENY