pandas 排序

参考
1. http://blog.csdn.net/shingle_/article/details/71480334

排序

sort_index-对行或列索引进行排序

import pandas as pd
from pandas import DataFrame,Series
obj=Series(range(6),index=['F','A','B','D','E','C'])
obj

结果:
F    0
A    1
B    2
D    3
E    4
C    5

#根据索引排序
obj.sort_index()
obj
结果:
A    1
B    2
C    5
D    3
E    4
F    0

对于二维DataFrame:

import numpy as np
frame = DataFrame(np.arange(8).reshape((2,4)), index=['B','A'],columns=['b','c','a','e'])
frame
    b   c   a   e
B   0   1   2   3
A   4   5   6   7
frame.sort_index()
结果:
    b   c   a   e
A   4   5   6   7
B   0   1   2   3
frame.sort_index(axis=1)
【out】:
    a   b   c   e
B   2   0   1   3
A   6   4   5   7
axis DataFrame的行用0,列用1
frame.sort_index(axis=1, ascending=False)
[out]:
    e   c   b   a
B   3   1   0   2
A   7   5   4   6

sort_values-按值进行排序

obj = Series([4, np.nan, 6, np.nan, -2, 2])
obj
[out]:
0    4.0
1    NaN
2    6.0
3    NaN
4   -2.0
5    2.0

排序:
obj.sort_values()
4   -2.0
5    2.0
0    4.0
2    6.0
1    NaN
3    NaN

在DataFrame上,根据一个或多个列中的值进行排序。将一个或多个列的名字传递给by选项即可达到该目的:

frame.sort_values(by='a')
    b   c   a   e
B   0   1   2   3
A   4   5   6   7

猜你喜欢

转载自blog.csdn.net/qq_26645205/article/details/78435857