pandas的函数应用二——排序
索引排序
1、Series排序
import pandas as pd
import numpy as np
s1 = pd.Series(np.arange(5),index=list('dcafb'))
s1
d 0
c 1
a 2
f 3
b 4
dtype: int32
a 2
b 4
c 1
d 0
f 3
dtype: int32
s1.sort_index(ascending=False) # 降序排列
f 3
d 0
c 1
b 4
a 2
dtype: int32
pd1 = pd.DataFrame(np.arange(12).reshape(4,3),index=list('dcab'),columns=list('BCA'))
pd1
|
B |
C |
A |
d |
0 |
1 |
2 |
c |
3 |
4 |
5 |
a |
6 |
7 |
8 |
b |
9 |
10 |
11 |
pd1.sort_index() # 默认升序,要想排序列,指定axis=1
|
B |
C |
A |
a |
6 |
7 |
8 |
b |
9 |
10 |
11 |
c |
3 |
4 |
5 |
d |
0 |
1 |
2 |
aa = pd1.sort_index(ascending=False) # 降序排列,不改变原来值,改变完赋给新的数据
aa
|
B |
C |
A |
d |
0 |
1 |
2 |
c |
3 |
4 |
5 |
b |
9 |
10 |
11 |
a |
6 |
7 |
8 |
值排序
根据值的大小进行排序,当有缺失值的时候,缺失值在最后。
|
B |
C |
A |
d |
0 |
1 |
2 |
c |
3 |
4 |
5 |
a |
6 |
7 |
8 |
b |
9 |
10 |
11 |
pd1.sort_values(by = 'B',ascending=False)
|
B |
C |
A |
b |
9 |
10 |
11 |
a |
6 |
7 |
8 |
c |
3 |
4 |
5 |
d |
0 |
1 |
2 |
pd1.loc['a','B']=9
pd1.loc['a','C']=18
pd1.sort_values(by = ['B','C'],ascending=False)
|
B |
C |
A |
a |
9 |
18 |
8 |
b |
9 |
10 |
11 |
c |
3 |
4 |
5 |
d |
0 |
1 |
2
|
志同道合一起学习,欢迎加入QQ群:878749917