一、定义数据框DataFrame
import pandas
frame = pandas.DataFrame({"a":[9,2,5,1],"b":[4,7,-3,2],"c":[6,5,8,3]})
frame
Out[53]:
a b c
0 9 4 6
1 2 7 5
2 5 -3 8
3 1 2 3
二、按列对DataFrame排序
1. 按1列排序
(1)升序
frame.sort(columns = ['a'],axis = 0,ascending = True)
Out[62]:
a b c
3 1 2 3
1 2 7 5
2 5 -3 8
0 9 4 6
frame.sort_index(axis = 0,ascending = True,by = 'a')
Out[63]:
a b c
3 1 2 3
1 2 7 5
2 5 -3 8
0 9 4 6
frame.sort_values(by = 'a',axis = 0,ascending = True)
Out[65]:
a b c
3 1 2 3
1 2 7 5
2 5 -3 8
0 9 4 6
(2)降序
frame.sort(columns = ['a'],axis = 0,ascending = False)
Out[67]:
a b c
0 9 4 6
2 5 -3 8
1 2 7 5
3 1 2 3
frame.sort_index(axis = 0,ascending = False,by = 'a')
Out[68]:
a b c
0 9 4 6
2 5 -3 8
1 2 7 5
3 1 2 3
frame.sort_values(by = 'a',axis = 0,ascending = False)Out[69]:
a b c
0 9 4 6
2 5 -3 8
1 2 7 5
3 1 2 3
2. 按多列排序
frame = pandas.DataFrame({"a":[9,2,5,1,0,7],"b":[4,7,-3,2,2,2],"c":[6,5,8,3,4,4]})
frame
Out[73]:
a b c
0 9 4 6
1 2 7 5
2 5 -3 8
3 1 2 3
4 0 2 4
5 7 2 4
(1)升序
frame.sort(columns = ['b','c','a'],axis = 0,ascending = True) Out[74]: a b c 2 5 -3 8 3 1 2 3 4 0 2 4 5 7 2 4 0 9 4 6 1 2 7 5 frame.sort_index(axis = 0,ascending = True,by = ['b','c','a']) Out[75]: a b c 2 5 -3 8 3 1 2 3 4 0 2 4 5 7 2 4 0 9 4 6 1 2 7 5 frame.sort_values(by = ['b','c','a'],axis = 0,ascending = True) Out[76]: a b c 2 5 -3 8 3 1 2 3 4 0 2 4 5 7 2 4 0 9 4 6 1 2 7 5
(2)降序
rame.sort(columns = ['b','c','a'],axis = 0,ascending = False)
Out[77]:
a b c
1 2 7 5
0 9 4 6
5 7 2 4
4 0 2 4
3 1 2 3
2 5 -3 8
frame.sort_index(axis = 0,ascending = False,by = ['b','c','a'])
Out[78]:
a b c
1 2 7 5
0 9 4 6
5 7 2 4
4 0 2 4
3 1 2 3
2 5 -3 8
frame.sort_values(by = ['b','c','a'],axis = 0,ascending = False)
Out[79]:
a b c
1 2 7 5
0 9 4 6
5 7 2 4
4 0 2 4
3 1 2 3
2 5 -3 8
三、按行对DataFrame排序
data = {"b":[4,7,-3,2,2,2],"a":[9,2,5,1,0,7],"c":[6,5,8,3,4,4]}
frame = pandas.DataFrame(data,columns = ['b','a','c'])
frame
Out[90]:
b a c
0 4 9 6
1 7 2 5
2 -3 5 8
3 2 1 3
4 2 0 4
5 2 7 4
1. 按行升序
frame.sort_index(axis = 1,ascending = True)
Out[91]:
a b c
0 9 4 6
1 2 7 5
2 5 -3 8
3 1 2 3
4 0 2 4
5 7 2 4
2. 按行降序
frame.sort_index(axis = 1,ascending = False)
Out[97]:
c b a
0 6 4 9
1 5 7 2
2 8 -3 5
3 3 2 1
4 4 2 0
5 4 2 7
原文链接 : https://blog.csdn.net/flyfrommath/article/details/77225733