pandas.Series.sort_index#

Series.sort_index(*, axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, ignore_index=False, key=None)[源代码]#

按索引标签对 Series 进行排序。

如果 inplace 参数为 False,则返回一个按标签排序的新 Series;否则,更新原始 Series 并返回 None。

Parameters:
axis{0 或 ‘index’}

未使用。参数是与 DataFrame 兼容性所必需的。

levelint, optional

如果不是 None,则按指定索引级别(或级别)上的值进行排序。

ascendingbool 或布尔值列表,默认为 True

升序与降序排序。当索引是 MultiIndex 时,可以针对每个级别单独控制排序方向。

inplacebool,默认 False

如果为 True,则原地执行操作。

kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’},默认为 ‘quicksort’

排序算法的选择。有关更多信息,请参阅 numpy.sort() 。’mergesort’ 和 ‘stable’ 是唯一稳定的算法。对于 DataFrame,此选项仅在按单个列或标签排序时应用。

na_position{‘first’, ‘last’},默认为 ‘last’

如果为 ‘first’,则将 NaN 放在开头;如果为 ‘last’,则将 NaN 放在末尾。不适用于 MultiIndex。

sort_remainingbool, default True

如果为 True 且按级别排序,并且索引是多级索引,则在按指定级别排序后,也按其他级别(按顺序)排序。

ignore_indexbool,默认 False

如果为 True,则生成的轴标签为 0, 1, …, n - 1。

keycallable,可选

如果不是 None,则在排序前将 key 函数应用于索引值。这类似于内置 sorted() 函数中的 key 参数,但有一个显著的区别是此 key 函数应该是*向量化的*。它应该接受一个 Index 并返回一个形状相同的 Index

Returns:
Series 或 None

按标签排序后的原始 Series,如果 inplace=True 则为 None。

参见

DataFrame.sort_index

按索引对 DataFrame 进行排序。

DataFrame.sort_values

按值对 DataFrame 进行排序。

Series.sort_values

按值对 Series 进行排序。

Examples

>>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, 4])
>>> s.sort_index()
1    c
2    b
3    a
4    d
dtype: object

降序排序

>>> s.sort_index(ascending=False)
4    d
3    a
2    b
1    c
dtype: object

默认情况下,NaNs 放在末尾,但可以使用 na_position 将它们放在开头。

>>> s = pd.Series(['a', 'b', 'c', 'd'], index=[3, 2, 1, np.nan])
>>> s.sort_index(na_position='first')
NaN     d
 1.0    c
 2.0    b
 3.0    a
dtype: object

指定要排序的索引级别。

>>> arrays = [np.array(['qux', 'qux', 'foo', 'foo',
...                     'baz', 'baz', 'bar', 'bar']),
...           np.array(['two', 'one', 'two', 'one',
...                     'two', 'one', 'two', 'one'])]
>>> s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index=arrays)
>>> s.sort_index(level=1)
bar  one    8
baz  one    6
foo  one    4
qux  one    2
bar  two    7
baz  two    5
foo  two    3
qux  two    1
dtype: int64

按级别排序时,不按剩余级别排序。

>>> s.sort_index(level=1, sort_remaining=False)
qux  one    2
foo  one    4
baz  one    6
bar  one    8
qux  two    1
foo  two    3
baz  two    5
bar  two    7
dtype: int64

在排序之前应用一个键函数。

>>> s = pd.Series([1, 2, 3, 4], index=['A', 'b', 'C', 'd'])
>>> s.sort_index(key=lambda x : x.str.lower())
A    1
b    2
C    3
d    4
dtype: int64