import numpy as np
import pandas as pd
from pandas import Series,DataFrame
Series
s = Series([3,1,7,0],index=['c','d','a','b'])
s.sort_index()
a 7
b 0
c 3
d 1
dtype: int64
DataFrame
df = DataFrame(np.arange(20).reshape(5,4),index=[3,1,2,4,6],columns=['d','c','a','b'])
print(df)
d c a b
3 0 1 2 3
1 4 5 6 7
2 8 9 10 11
4 12 13 14 15
6 16 17 18 19
行索引排序
print(df.sort_index(ascending=False)) # 降序排列
d c a b
6 16 17 18 19
4 12 13 14 15
3 0 1 2 3
2 8 9 10 11
1 4 5 6 7
列索引排序
print(df.sort_index(axis=1))
a b c d
3 2 3 1 0
1 6 7 5 4
2 10 11 9 8
4 14 15 13 12
6 18 19 17 16
Series
s.sort_values()
b 0
d 1
c 3
a 7
dtype: int64
DataFrame
按多列值进行排序
print(df.sort_values(by=['a','b']))
d c a b
3 0 1 2 3
1 4 5 6 7
2 8 9 10 11
4 12 13 14 15
6 16 17 18 19
按多行值进行排序
print(df.sort_values(by=[2,6],axis=1))
d c a b
3 0 1 2 3
1 4 5 6 7
2 8 9 10 11
4 12 13 14 15
6 16 17 18 19
o = Series([7,-5,7,4,2,0,4,7])
o.rank()
0 7.0
1 1.0
2 7.0
3 4.5
4 3.0
5 2.0
6 4.5
7 7.0
dtype: float64
o.rank(method='first')
0 6.0
1 1.0
2 7.0
3 4.0
4 3.0
5 2.0
6 5.0
7 8.0
dtype: float64
o.rank(method='max')
0 8.0
1 1.0
2 8.0
3 5.0
4 3.0
5 2.0
6 5.0
7 8.0
dtype: float64