pandas 大熊猫 value_counts() 主要按降序排序,其次按升序排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31431553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:37:38  来源:igfitidea点击:

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

python-3.xpandas

提问by eyaler

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.

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

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

如何将每个相同计数中的值按升序排序?

apples    5
peaches   5
bananas   3
carrots   3
apricots  1

回答by JohnE

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:

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

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.

我实际上在默认情况下得到了相同的结果,所以这里有一个测试ascending=[False,False]来证明这实际上是按照建议工作的。

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 ascendingkeyword argument.

我实际上对这里在升序和降序方面究竟需要什么输出有点困惑,但无论如何,这里有 4 种可能的组合,你可以通过改变ascending关键字参数来获得它。