當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python 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)

按索引標簽對係列進行排序。

如果 inplace 參數是 False ,則返回按標簽排序的新係列,否則更新原始係列並返回無。

參數

axis整數,默認 0

軸直接排序。對於係列,這隻能是 0。

level整數,可選

如果不是無,則對指定索引級別的值進行排序。

ascendingbool 或 list-like of bools,默認 True

升序與降序排序。當索引是 MultiIndex 時,可以單獨控製每個級別的排序方向。

inplace布爾值,默認為 False

如果為 True,則就地執行操作。

kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’},默認 ‘quicksort’

排序算法的選擇。另請參閱numpy.sort() 了解更多信息。 ‘mergesort’ and ‘stable’ 是唯一穩定的算法。對於 DataFrame,此選項僅在對單個列或標簽進行排序時應用。

na_position{‘first’, ‘last’},默認 ‘last’

如果 ‘first’ 將 NaN 放在開頭,則 ‘last’ 將 NaN 放在末尾。未針對 MultiIndex 實施。

sort_remaining布爾值,默認為真

如果 True 並且按級別和索引排序是多級的,則在按指定級別排序後也按其他級別排序(按順序)。

ignore_index布爾值,默認為 False

如果為 True,則生成的軸將標記為 0、1、...、n - 1。

key可調用的,可選的

如果不是 None,則在排序之前將 key 函數應用於索引值。這與內置sorted() 函數中的key 參數類似,但顯著的區別是該key 函數應該被矢量化。它應該期望 Index 並返回相同形狀的 Index

返回

係列或無

原始係列按標簽排序,如果 inplace=True 則為無。

例子

>>> 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

就地排序

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

默認情況下,NaN 放在最後,但使用 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

相關用法


注:本文由純淨天空篩選整理自pandas.pydata.org大神的英文原創作品 pandas.Series.sort_index。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。