1、排序和排名
根据条件对数据集排序(sorting)也是一种重要的内置运算。要对行或列索引进行排序(按字典顺序),可使用sort_index方法,它将返回一个已排序的新对象:
In [80]: obj = pd.Series(range(4), index=['d', 'a', 'b', 'c'])
In [81]: obj.sort_index()
Out[81]:
a 1
b 2
c 3
d 0
dtype: int64
而对于DataFrame,则可以根据任意一个轴上的索引进行排序:
In [82]: frame = pd.DataFrame(np.arange(8).reshape((2, 4)), index=['three', 'one'], columns=['d', 'a', 'b', 'c'])
In [83]: frame.sort_index()
Out[83]:
d a b c
one 4 5 6 7
three 0 1 2 3
[2 rows x 4 columns]
In [84]: frame.sort_index(axis=1)
Out[84]:
a b c d
three 1 2 3 0
one 5 6 7 4
[2 rows x 4 columns]
数据默认是按升序排序的,但也可以降序排序:
In [85]: frame.sort_index(axis=1, ascending=False)
Out[85]:
d c b a
three 0 3 2 1
one 4 7 6 5
[2 rows x 4 columns]
若要按值对Series进行排序,可使用其order方法:
In [86]: obj = pd.Series([4, 7, -3, 2])
In [87]: obj.order()
Out[87]:
2 -3
3 2
0 4
1 7
dtype: int64
在排序时,任何缺失值默认都会被放到Series的末尾:
In [88]: obj = pd.Series([4, np.nan, 7, np.nan, -3, 2])
In [89]: obj.order()
Out[89]:
4 -3
5 2
0 4
2 7
1 NaN
3 NaN
dtype: float64
在DataFrame上,你可能希望根据一个或多个列中的值进行排序。将一个或多个列的名字传递给by选项即可达到该目的:
In [90]: frame = pd.DataFrame({'b': [4, 7, -3, 2], 'a': [0, 1, 0, 1]})
In [91]: frame
Out[91]:
a b
0 0 4
1 1 7
2 0 -3
3 1 2
[4 rows x 2 columns]
In [92]: frame.sort_index(by='b')
Out[92]:
a b<