大 pandas value_counts() 主要按降序排序,其次按升序排序 [英] sort pandas value_counts() primarily by descending counts and secondarily by ascending values

查看:159
本文介绍了大 pandas value_counts() 主要按降序排序,其次按升序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将 value_counts() 应用于 pandas 中的系列时,默认情况下,计数按降序排序,但不会在每个计数内对值进行排序.

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

推荐答案

value_counts 的输出本身就是一个系列(就像输入一样),因此您可以使用任何系列的所有标准排序选项.例如:

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

我实际上在默认情况下得到了相同的结果,因此这里使用 ascending=[False,False] 进行测试,以证明这实际上按建议工作.

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

实际上,我对升序和降序的确切输出结果有点困惑,但无论如何,这里有 4 种可能的组合,您可以通过更改 ascending 关键字参数.

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.

这篇关于大 pandas value_counts() 主要按降序排序,其次按升序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆