Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

python - changing sort in value_counts

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...