按索引对DataFrame或Series进行排序(注意ascending=false的意思是按照降序排序,若不写参数则默认升序排序)
DataFrame的构造函数默认参数是(值,列名,行索引),行索引不填则默认0,1,2,3这样?
In [101]: frame=pd.DataFrame(np.arange(12).reshape((4,3)),columns=['c','a','b'],index=['D','B','C','A'])c a b
D 0 1 2
B 3 4 5
C 6 7 8
A 9 10 11In [102]: frame.sort_index(axis=0)
Out[102]:c a b
A 9 10 11
B 3 4 5
C 6 7 8
D 0 1 2In [103]: frame.sort_index(axis=1)
Out[103]:a b c
D 1 2 0
B 4 5 3
C 7 8 6
A 10 11 9In [105]: frame.sort_index(axis=1,ascending=False)
Out[105]:c b a
D 0 2 1
B 3 5 4
C 6 8 7
A 9 11 10
按指定的值对DataFrame进行排序
In [133]: frame.sort_index(by=['b'],ascending=False)
Out[133]:c a b
A 9 10 11
C 6 7 8
B 3 4 5
D 0 1 2
按值对Series进行排序
In [125]: obj=pd.Series([4,7,-3,2])In [126]: obj.sort_values()
Out[126]:
2 -3
3 2
0 4
1 7
dtype: int64
部分内容参考博文