rank函数python_在Python中计算列表排名向量的有效方法

I'm looking for an efficient way to calculate the rank vector of a list in Python, similar to R's rank function. In a simple list with no ties between the elements, element i of the rank vector of a list l should be x if and only if l[i] is the x-th element in the sorted list. This is simple so far, the following code snippet does the trick:

def rank_simple(vector):

return sorted(range(len(vector)), key=vector.__getitem__)

Things get complicated, however, if the original list has ties (i.e. multiple elements with the same value). In that case, all the elements having the same value should have the same rank, which is the average of their ranks obtained using the naive method above. So, for instance, if I have [1, 2, 3, 3, 3, 4, 5], the naive ranking gives me [0, 1, 2, 3, 4, 5, 6], but what I would like to have is [0, 1, 3, 3, 3, 5, 6]. Which one would be the most efficient way to do this in Python?

Footnote: I don't know if NumPy already has a method to achieve this or not; if it does, please let me know, but I would be interested in a pure Python solution anyway as I'm developing a tool which should work without NumPy as well.

解决方案

Using scipy, the function you are looking for is scipy.stats.rankdata :

In [13]: import scipy.stats as ss

In [19]: ss.rankdata([3, 1, 4, 15, 92])

Out[19]: array([ 2., 1., 3., 4., 5.])

In [20]: ss.rankdata([1, 2, 3, 3, 3, 4, 5])

Out[20]: array([ 1., 2., 4., 4., 4., 6., 7.])

The ranks start at 1, rather than 0 (as in your example), but then again, that's the way R's rank function works as well.

Here is a pure-python equivalent of scipy's rankdata function:

def rank_simple(vector):

return sorted(range(len(vector)), key=vector.__getitem__)

def rankdata(a):

n = len(a)

ivec=rank_simple(a)

svec=[a[rank] for rank in ivec]

sumranks = 0

dupcount = 0

newarray = [0]*n

for i in xrange(n):

sumranks += i

dupcount += 1

if i==n-1 or svec[i] != svec[i+1]:

averank = sumranks / float(dupcount) + 1

for j in xrange(i-dupcount+1,i+1):

newarray[ivec[j]] = averank

sumranks = 0

dupcount = 0

return newarray

print(rankdata([3, 1, 4, 15, 92]))

# [2.0, 1.0, 3.0, 4.0, 5.0]

print(rankdata([1, 2, 3, 3, 3, 4, 5]))

# [1.0, 2.0, 4.0, 4.0, 4.0, 6.0, 7.0]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值