pandas Series.value_counts returns inconsistent order for equal count strings

后端 未结 3 2016
野性不改
野性不改 2021-01-12 14:38

When I run the code below:

s = pandas.Series([\'c\', \'a\', \'b\', \'a\', \'b\'])
print(s.value_counts())

Sometimes I get this:

<         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 15:20

    You could use sort_index:

    print(df.value_counts().sort_index())
    

    Output:

    a    1
    b    1
    dtype: int64
    

    Please see the documentation if you want to use parameters (like ascending=True etc.)

    sort_index vs reindex(df.unique()) (as suggested by @Wen) seem to be perform quite similar:

    df.value_counts().sort_index():         1000 loops, best of 3: 636 µs per loop
    df.value_counts().reindex(df.unique()): 1000 loops, best of 3: 880 µs per loop
    

提交回复
热议问题