优快云上看到几篇有关rank函数的介绍,都是引用了以下同一个例子:
obj = pd.Series([7,-5,7,4,2,0,4])
obj.rank()
输出为:
0 6.5
1 1.0
2 6.5
3 4.5
4 3.0
5 2.0
6 4.5
这个例子源于《利用Python进行数据分析》一书,书中没有介绍各项数值是怎么来的,只提到rank是通过”为各组分配一个平均排名“,大家也没有进一步说明rank过后的各项数值怎么来的,现在换个例子:
假设在-15和20间随机生成20个整数,看看序列的变化
obj2=Series(np.random.randint(-15,20,size=20)) #在-15和20间随机生成20个整数
'''对以下三个进行比较'''
obj2 #原始序列
obj2.sort_values() #将原始序列排序
obj2.rank() #将原始序列排名
得到的数据放入同一表中比较:
obj2 | obj2.rank() | obj2.sort_values() | ||
0 -11 1 0 2 4 3 14 4 -11 5 -4 6 1 7 -6 8 13 9 -2 10 -10 11 -11 12 -3 13 6 14 4 15 -4 16 10 17 -12 18 16 19 13 dtype: int32 | 0 3.0 1 11.0 2 13.5 3 19.0 4 3.0 5 7.5 6 12.0 7 6.0 8 17.5 9 10.0 10 5.0 11 3.0 12 9.0 13 15.0 14 13.5 15 7.5 16 16.0 17 1.0 18 20.0 19 17.5 dtype: float64 | 17 -12 0 -11 4 -11 11 -11 10 -10 7 -6 15 -4 5 -4 12 -3 9 -2 1 0 6 1 14 4 2 4 13 6 16 10 8 13 19 13 3 14 18 16 dtype: int32 |
从上表比较可以发现:
原始序列index为8和19的两个数值相同,均为13,它们在obj2.sort_values()按大小排序为第17、18位,两者的平均值为17.5,这个17.5就是obj2.rank()中index为8和19对应的值。同样地,在obj2.sort_values()中数值为-4的有两个,对应原始序列index为15和5,它们在obj2.sort_values()中拍第7、8位,因此在obj2.rank()中的数值等于(7+8)/2=7.5。
再看obj2.sort_values()中三个数值同为-11的3行分别是第2、3、4位,其平均值为(2+3+4)/3=3,因此在obj2.rank()中的数值等于3的有三个,对应的index为0,4,11.
最后,看看obj2.sort_values()中没有多个相同数值的行,如第12行数值为1只有一个,其在原始序列中为第6行,也就是说obj2.rank()中index为6对应的就是12。
补充下:如果一列数值中,最小值的只有一个,那么rank()最小的始终为1,如果有多个,为(1+2+……+n)/n
相同的还有
obj2.rank(method='first')
obj2 | obj2.rank() | obj2.sort_values() | obj2.rank(method='first') | |||
0 -11 1 0 2 4 3 14 4 -11 5 -4 6 1 7 -6 8 13 9 -2 10 -10 11 -11 12 -3 13 6 14 4 15 -4 16 10 17 -12 18 16 19 13 dtype: int32 | 0 3.0 1 11.0 2 13.5 3 19.0 4 3.0 5 7.5 6 12.0 7 6.0 8 17.5 9 10.0 10 5.0 11 3.0 12 9.0 13 15.0 14 13.5 15 7.5 16 16.0 17 1.0 18 20.0 19 17.5 dtype: float64 | 17 -12 0 -11 4 -11 11 -11 10 -10 7 -6 15 -4 5 -4 12 -3 9 -2 1 0 6 1 14 4 2 4 13 6 16 10 8 13 19 13 3 14 18 16 dtype: int32 | 0 2.0 |