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: let me know if there's a NumPy method to achieve this; but I am interested in a pure Python solution anyway as I'm developing a tool which should work without NumPy as well.
numpy.argsort(vector)
? – Copyreadrank_simple()
actually the equivalent of R'sorder()
function, instead ofrank()
? See e.g. https://mcmap.net/q/103427/-rank-and-order-in-r. – Muleteerrank()
fucntion allow you to specify any of those, as well as 'first', 'last', 'random'. – Loudermilk