0

Having a list of numbers such as [968, 233, 493, 5, 851, 224, 871, 396, 689, 862] I would like to get a rank of each of them, where the highest number gets the lowest rank.

By using scipy.stats.rankdata I get this array([10., 3., 5., 1., 7., 2., 9., 4., 6., 8.]).

The problem is that the ranks are given assuming sorting the list in ascending order. How can I get the ranks assuming descending order of sorting given rankdata doesn't take this as a parameter?

2 Answers2

2

Another way to do it is to multiply each element by (-1):

import numpy as np
import scipy

a = np.array([968, 233, 493, 5, 851, 224, 871, 396, 689, 862])
scipy.stats.rankdata(-a)

It gives:

array([ 1.,  8.,  6., 10.,  4.,  9.,  2.,  7.,  5.,  3.])
bb1
  • 7,174
  • 2
  • 8
  • 23
1

If you do not have to use rankdata you can use numpy argsort.

import numpy as np
inds = np.argsort(arr)
ranks = np.empty_like(inds)
ranks[inds] = np.arange(len(arr),0,-1)

should give you the results you want.

This works by getting the ordering of the elements of the original array using argsort, and then populating a new array using a descending list of numbers in order.

C Haworth
  • 659
  • 3
  • 12