データ分析のpandas順位rank()の理解


pandasのrank()は順位付けができます
from pandas import Series

obj = Series([7, -5, 7, 4, 2, 0, 4])
print(obj.rank())

出力は
0    6.5
1    1.0
2    6.5
3    4.5
4    3.0
5    2.0
6    4.5
dtype: float64

その順位の原理は,objを先に並べ替え,対応する順位を得ることである.
[-5, 0, 2, 4, 4, 7, 7]
  |  |  |  |  |  |  |
  1  2  3  4  5  6  7

 
しかしrankのデフォルトは平均順位なので
4の順位は(4+5)/2=4.5
7の順位は(6+7)/2=6.5
他にも同じ理屈があるから
0    6.5 -->7
1    1.0 -->-5
2    6.5 -->7
3    4.5 -->4
4    3.0 -->2
5    2.0 -->0
6    4.5 -->4
dtype: float64

キーワードmethodで他のランキング方式method=‘first’,‘max’などを得ることができる
print(obj.rank(method='first'))

0    6.0
1    1.0
2    7.0
3    4.0
4    3.0
5    2.0
6    5.0
dtype: float64