Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort pandas value_counts() primarily by descending counts and secondarily by ascending values

When applying value_counts() to a series in pandas, by default the counts are sorted in descending order, however the values are not sorted within each count.

How can i have the values within each identical count sorted in ascending order?

apples    5
peaches   5
bananas   3
carrots   3
apricots  1
like image 548
o17t H1H' S'k Avatar asked Dec 31 '25 10:12

o17t H1H' S'k


1 Answers

The output of value_counts is a series itself (just like the input), so you have available all of the standard sorting options as with any series. For example:

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

df.fruit.value_counts().reset_index().sort([0,'index'],ascending=[False,True])

      index  0
0    apples  5
1   peaches  5
2   bananas  3
3   carrots  3
4  apricots  1

I'm actually getting the same results by default so here's a test with ascending=[False,False] to demonstrate that this is actually working as suggested.

df.fruit.value_counts().reset_index().sort([0,'index'],ascending=[False,False])

      index  0
1   peaches  5
0    apples  5
3   carrots  3
2   bananas  3
4  apricots  1

I'm actually a bit confused about exactly what desired output here in terms of ascending vs descending, but regardless, there are 4 possible combos here and you can get it however you like by altering the ascending keyword argument.

like image 88
JohnE Avatar answered Jan 02 '26 09:01

JohnE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!