首页 > 编程笔记

Pandas Series对象排序方法详解

Series 提供了若干排序的方法。其中,argsort 方法给出了排序的索引,rank 方法直接给出了顺序,而 sort_values 和 sort_index 则分别是按值和索引排序。示例代码如下。
In [1]: import pandas as pd
In [2]: a=pd.Series([3,1,2])

1) argsort()

与 Numpy 中的 argsort 方法类似,返回从小到大排名的索引。
In [3]: a.argsort()  # 返回排名索引
Out[3]: 
0    1
1    2
2    0
dtype: int64

2)rank()

rank 方法直接返回各个值的排名顺序。
In [4]: a.rank()  # 排名
Out[4]: 
0    3.0
1    1.0
2    2.0
dtype: float64

3) sort_values()

sort_values 方法默认按从小到大的顺序对序列进行排序。
In [5]: a=a.sort_values()  # 按值排序
In [6]: a
Out[6]: 
1    1
2    2
0    3
dtype: int64

3) sort_index()

sort_index 方法默认是按从小到大的顺序对索引进行排序。
In [7]: a.sort_index() #按索引排序
Out[7]: 
0    3
1    1
2    2
dtype: int64 

优秀文章