当我运行下面的代码时:
s = pandas.Series(['c', 'a', 'b', 'a', 'b'])
print(s.value_counts())
有时我会这样:
a 2
b 2
c 1
dtype: int64
有时我会这样:
b 2
a 2
c 1
dtype: int64
例如为等效计数返回的索引顺序不同。如果系列值是整数而不是字符串,我无法重现这一点。
为什么会发生这种情况,每次获得相同索引顺序的最有效方法是什么?
我希望它仍然按计数降序排序,但要与等价项的顺序保持一致。
我正在运行 Python 3.7.0 和 pandas 0.23.4
最佳答案
您有几个选项可以对给定的系列进行一致排序:
s = pd.Series(['a', 'b', 'a', 'c', 'c'])
c = s.value_counts()
按索引排序
res = c.sort_index()
a 2
b 1
c 2
dtype: int64
按计数排序(任意并列)
对于递减计数,什么也不做,因为这是默认设置。否则,您可以使用 pd.Series.sort_values
,默认为 ascending=True
。在任何一种情况下,您都不应该对领带的处理方式做出任何假设。
res = c.sort_values()
b 1
c 2
a 2
dtype: int64
为了更高效,您可以使用 c.iloc[::-1]
来反转顺序。
先按计数再按索引排序
您可以使用 numpy.lexsort
按计数排序,然后按索引排序。请注意相反的顺序,即 -c.values
首先用于排序。
res = c.iloc[np.lexsort((c.index, -c.values))]
a 2
c 2
b 1
dtype: int64
关于python - pandas Series.value_counts 返回相等计数字符串的不一致顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51933763/