Efficient method to calculate the rank vector of a list in Python

Posted by Tamás on Stack Overflow See other posts from Stack Overflow or by Tamás
Published on 2010-06-18T16:27:08Z Indexed on 2010/06/18 16:33 UTC
Read the original article Hit count: 295

Filed under:
|
|
|

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 [rank for rank in sorted(range(n), 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.

© Stack Overflow or respective owner

Related posts about python

Related posts about list