Python 更改 value_counts 中的排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43855474/
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
changing sort in value_counts
提问by Mark Ginsburg
If I do
如果我做
mt = mobile.PattLen.value_counts() # sort True by default
I get
我得到
4 2831
3 2555
5 1561
[...]
If I do
如果我做
mt = mobile.PattLen.value_counts(sort=False)
I get
我得到
8 225
9 120
2 1234
[...]
What I am trying to do is get the output in 2, 3, 4 ascending order (the left numeric column). Can I change value_counts somehow or do I need to use a different function.
我想要做的是按 2、3、4 升序(左侧数字列)获取输出。我可以以某种方式更改 value_counts 还是需要使用不同的函数。
回答by jezrael
I think you need sort_index
, because the left column is called index
. The full command would be mt = mobile.PattLen.value_counts().sort_index()
. For example:
我认为你需要sort_index
,因为左边的列被称为index
. 完整的命令是mt = mobile.PattLen.value_counts().sort_index()
. 例如:
mobile = pd.DataFrame({'PattLen':[1,1,2,6,6,7,7,7,7,8]})
print (mobile)
PattLen
0 1
1 1
2 2
3 6
4 6
5 7
6 7
7 7
8 7
9 8
print (mobile.PattLen.value_counts())
7 4
6 2
1 2
8 1
2 1
Name: PattLen, dtype: int64
mt = mobile.PattLen.value_counts().sort_index()
print (mt)
1 2
2 1
6 2
7 4
8 1
Name: PattLen, dtype: int64