pandas.Series.sort_values#

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

按值排序。

按某种标准按升序或降序对系列进行排序。

参数
axis{0或‘index’},默认为0

轴指向直接排序。为了与DataFrame.ort_Values兼容,接受值‘index’。

ascending布尔值或布尔值列表,默认为真

如果为True,则按升序排序值,否则按降序排序值。

inplace布尔值,默认为False

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

kind{‘快速排序’,‘合并排序’,‘堆排序’,‘稳定’},默认‘快速排序’

排序算法的选择。另请参阅 numpy.sort() 以获取更多信息。“合并排序”和“稳定”是唯一稳定的算法。

na_position{‘First’或‘Last’},默认为‘Last’

论元‘first’把‘nans’放在开头,‘last’把nans放在末尾。

ignore_index布尔值,默认为False

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

1.0.0 新版功能.

key可调用,可选

如果不是无,则在排序前将键函数应用于序列值。这类似于 key 建筑中的参数 sorted() 函数,但显著不同的是,这 key 函数应为 矢量化 。它应该期待一个 Series 并返回一个类似数组的。

1.1.0 新版功能.

退货
系列或无

按值排序的序列或无(如果 inplace=True

参见

Series.sort_index

按系列索引排序。

DataFrame.sort_values

按任一轴上的值对DataFrame进行排序。

DataFrame.sort_index

按索引对DataFrame进行排序。

示例

>>> s = pd.Series([np.nan, 1, 3, 10, 5])
>>> s
0     NaN
1     1.0
2     3.0
3     10.0
4     5.0
dtype: float64

按升序排序值(默认行为)

>>> s.sort_values(ascending=True)
1     1.0
2     3.0
4     5.0
3    10.0
0     NaN
dtype: float64

按降序对值进行排序

>>> s.sort_values(ascending=False)
3    10.0
4     5.0
2     3.0
1     1.0
0     NaN
dtype: float64

就地排序值

>>> s.sort_values(ascending=False, inplace=True)
>>> s
3    10.0
4     5.0
2     3.0
1     1.0
0     NaN
dtype: float64

排序值,将Nas放在第一位

>>> s.sort_values(na_position='first')
0     NaN
1     1.0
2     3.0
4     5.0
3    10.0
dtype: float64

对一系列字符串进行排序

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

使用键函数进行排序。你的 key 函数将被赋予 Series 值的值,并应返回类似数组的。

>>> s = pd.Series(['a', 'B', 'c', 'D', 'e'])
>>> s.sort_values()
1    B
3    D
0    a
2    c
4    e
dtype: object
>>> s.sort_values(key=lambda x: x.str.lower())
0    a
1    B
2    c
3    D
4    e
dtype: object

NumPy功能在这里运行得很好。例如,我们可以按 sin 价值的

>>> s = pd.Series([-4, -2, 0, 2, 4])
>>> s.sort_values(key=np.sin)
1   -2
4    4
2    0
0   -4
3    2
dtype: int64

可以使用更复杂的用户定义函数,只要它们需要Series并返回类似数组的

>>> s.sort_values(key=lambda x: (np.tan(x.cumsum())))
0   -4
3    2
4    4
1   -2
2    0
dtype: int64