約定:
import pandas as pd
import numpy as np
排序和排名
根據條件對Series對象或DataFrame對象的值排序(sorting)和排名(ranking)是一種重要的内置運算。
接下來為大家介紹如何使用pandas對象的:sort_index() / sort_values() / rank() 方法。
一、對Series排序
對Series對象排序是最常用的,可以根據Series對象的索引、值排序。
- 根據索引排序
se1=pd.Series(np.arange(,),index=[,,])
se1.sort_index()
代碼結果:
1 10
2 12
3 11
dtype: int32
- 還能對字元索引排序
se2=pd.Series(np.arange(,),index=['c','d','a'])
se2.sort_index()
代碼結果:
a 2
c 0
d 1
dtype: int32
- 按降序排序
se2.sort_index(ascending=False)
代碼結果:
d 1
c 0
a 2
dtype: int32
- 按值排序
se3=pd.Series([,-,])
se3.sort_values()
代碼結果:
1 -5
0 3
2 7
dtype: int64
- NaN值會放在Series末尾
se4=pd.Series([,np.nan,-,np.nan,])
se4.sort_values()
代碼結果:
2 -7.0
0 3.0
4 5.0
1 NaN
3 NaN
dtype: float64
二、對DataFrame排序
- 通過axis參數可以對任意軸排序
df1=pd.DataFrame(np.arange().reshape(,),index=list("bac"),columns=list("yzx"))
df1
代碼結果:
y | z | x | |
---|---|---|---|
b | 1 | 2 | |
a | 3 | 4 | 5 |
c | 6 | 7 | 8 |
df1.sort_index()
代碼結果:
y | z | x | |
---|---|---|---|
a | 3 | 4 | 5 |
b | 1 | 2 | |
c | 6 | 7 | 8 |
df1.sort_index(axis=)
代碼結果:
x | y | z | |
---|---|---|---|
b | 2 | 1 | |
a | 5 | 3 | 4 |
c | 8 | 6 | 7 |
- 根據一個列的值來排序
df2=pd.DataFrame({'a':[,,],'b':[,-,]})
df2.sort_values(by='b')
代碼結果:
a | b | |
---|---|---|
1 | 3 | -6 |
20 | 1 | |
2 | 3 | 18 |
- 對多個列來排序
df2.sort_values(by=['a','b'])
代碼結果:
a | b | |
---|---|---|
1 | 3 | -6 |
2 | 3 | 18 |
20 | 1 |
三、排名
排名是根據Series對象或DataFrame的某幾列的值進行排名,.rank(method=,ascending=,…)傳回對值的排名。但需要十分注意如何處理出現相同的值。
- 平均排名
為相同的值配置設定一個平均排名
se5=pd.Series([,,,,,])
se5.rank()
代碼結果:
0 1.0
1 2.5
2 5.5
3 4.0
4 2.5
5 5.5
dtype: float64
- 順序排名
對于相同的值按照出現的順序排名
se5.rank(method="first")
代碼結果:
0 1.0
1 2.0
2 5.0
3 4.0
4 3.0
5 6.0
dtype: float64
- 最小值排名
對于相同的值都取小的排名
se5.rank(method="min",ascending=False)
代碼結果:
0 6.0
1 4.0
2 1.0
3 3.0
4 4.0
5 1.0
dtype: float64
- 最大值排名
對于相同的值都取大的排名
se5.rank(method="max",ascending=False)
代碼結果:
0 6.0
1 5.0
2 2.0
3 3.0
4 5.0
5 2.0
dtype: float64
- 降序排名
se5.rank(method="first",ascending=False)
代碼結果:
0 6.0
1 4.0
2 1.0
3 3.0
4 5.0
5 2.0
dtype: float64
謝謝大家的浏覽,
希望我的努力能幫助到您,
共勉!