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
否则,将更新原始序列并返回None。- 参数
- axis整型,默认为0
轴指向直接排序。对于系列,该值只能为0。
- level整型,可选
如果不是无,则对指定索引级别中的值进行排序。
- ascending布尔型或类似列表型布尔型,默认为True
升序和降序排序。当索引为多索引时,可以单独控制每个级别的排序方向。
- inplace布尔值,默认为False
如果为True,则就地执行操作。
- kind{‘快速排序’,‘合并排序’,‘堆排序’,‘稳定’},默认‘快速排序’
排序算法的选择。另请参阅
numpy.sort()
以获取更多信息。“合并排序”和“稳定”是唯一稳定的算法。对于DataFrames,此选项仅在对单个列或标签进行排序时应用。- na_position{‘First’,‘Last’},默认为‘Last’
如果‘first’把‘nans’放在开头,‘last’把‘nans’放在最后。未为多索引实现。
- sort_remaining布尔值,默认为True
如果为True且按级别和索引排序为多级,则在按指定级别排序后也按其他级别排序(按顺序)。
- ignore_index布尔值,默认为False
如果为True,则生成的轴将标记为0,1,…,n-1。
1.0.0 新版功能.
- key可调用,可选
如果不是无,则在排序前将键函数应用于索引值。这类似于 key 建筑中的参数
sorted()
函数,但显著不同的是,这 key 函数应为 矢量化 。它应该期待一个Index
并返回一个Index
同样的形状。1.1.0 新版功能.
- 退货
- 系列或无
按标签排序的原始系列或无(如果
inplace=True
。
参见
DataFrame.sort_index
按索引对DataFrame进行排序。
DataFrame.sort_values
按值对DataFrame进行排序。
Series.sort_values
按值对系列进行排序。
示例
>>> 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