Pandas有两种排序方式,它们分别是:
- 按标签
- 按实际值
下面来看看一个输出的例子。
import pandas as pd
import numpy as np
unsorted_df=pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns=['col2','col1'])
unsorted_df
col2 | col1 | |
---|---|---|
1 | 1.277949 | 2.206393 |
4 | -2.278937 | 0.275532 |
6 | 0.194783 | 0.368292 |
2 | 0.034584 | 0.099397 |
3 | 0.492007 | -0.104609 |
5 | 2.238045 | -0.015054 |
9 | 0.030045 | 0.061799 |
8 | -0.148092 | 0.761345 |
0 | -1.448595 | 0.886345 |
7 | -1.007094 | 0.029695 |
unsorted_df.sort_index()
col2 | col1 | |
---|---|---|
0 | -1.448595 | 0.886345 |
1 | 1.277949 | 2.206393 |
2 | 0.034584 | 0.099397 |
3 | 0.492007 | -0.104609 |
4 | -2.278937 | 0.275532 |
5 | 2.238045 | -0.015054 |
6 | 0.194783 | 0.368292 |
7 | -1.007094 | 0.029695 |
8 | -0.148092 | 0.761345 |
9 | 0.030045 | 0.061799 |
unsorted_df.sort_index(ascending=False)
col2 | col1 | |
---|---|---|
9 | 0.030045 | 0.061799 |
8 | -0.148092 | 0.761345 |
7 | -1.007094 | 0.029695 |
6 | 0.194783 | 0.368292 |
5 | 2.238045 | -0.015054 |
4 | -2.278937 | 0.275532 |
3 | 0.492007 | -0.104609 |
2 | 0.034584 | 0.099397 |
1 | 1.277949 | 2.206393 |
0 | -1.448595 | 0.886345 |
unsorted_df.sort_index(axis=1)
col1 | col2 | |
---|---|---|
1 | 2.206393 | 1.277949 |
4 | 0.275532 | -2.278937 |
6 | 0.368292 | 0.194783 |
2 | 0.099397 | 0.034584 |
3 | -0.104609 | 0.492007 |
5 | -0.015054 | 2.238045 |
9 | 0.061799 | 0.030045 |
8 | 0.761345 | -0.148092 |
0 | 0.886345 | -1.448595 |
7 | 0.029695 | -1.007094 |
unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]})
unsorted_df.sort_values(by='col1')
col1 | col2 | |
---|---|---|
1 | 1 | 3 |
2 | 1 | 2 |
3 | 1 | 4 |
0 | 2 | 1 |
注意: 观察上面的输出结果,col1
值被排序,相应的 col2
值和行索引将随 col1
一起改变。
因此,它们看起来没有排序。
通过 by
参数指定需要列值,参考以下示例代码:
unsorted_df.sort_values(by=['col1','col2'])
col1 | col2 | |
---|---|---|
2 | 1 | 2 |
1 | 1 | 3 |
3 | 1 | 4 |
0 | 2 | 1 |
unsorted_df.sort_values(by='col1' ,kind='mergesort')
col1 | col2 | |
---|---|---|
1 | 1 | 3 |
2 | 1 | 2 |
3 | 1 | 4 |
0 | 2 | 1 |