根据值和索引对 pandas 系列进行排序

Sort pandas Series both on values and index

我想按值降序对 Series 进行排序,但我还需要遵守索引的字母顺序。 假设系列是这样的:

(index)
a         2
b         5
d         3
z         1
t         1
g         2
n         3
l         6
f         6
f         7

需要转成下面的Series,不用转DataFrame再转成Series,

输出:

(index)
f         7
f         6
l         6
b         5
d         3
n         3
a         2
g         2
t         1
z         1

我用过lexsort,但不合适。它按升序对值和索引进行排序。

Series.sort_values(axis=0, ascending=False)

根据您提供的信息,您是否可以尝试一下。

您可以先对索引进行排序,然后用稳定的算法对值进行排序:

s.sort_index().sort_values(ascending=False, kind='stable')

输出:

f    7
l    6
b    5
d    3
n    3
a    2
g    2
t    1
z    1
dtype: int64

使用的输入:

s = pd.Series({'a': 2, 'b': 5, 'd': 3, 'z': 1, 't': 1, 'g': 2, 'n': 3, 'l': 6, 'f': 7})

终于找到代码解决方案:

y = s.nlargest(n) 

n:最大值到return的个数。