[SciPy-User] Ranking a list of numbers

Keith Goodman kwgoodman@gmail....
Thu Jun 3 09:32:21 CDT 2010


On Thu, Jun 3, 2010 at 7:20 AM, Jose Gomez-Dans <jgomezdans@gmail.com> wrote:
> Hi,
> I've done this with loops, but I am sure there is a much nicer way of doing
> it with a couple of index tricks.
> Let's say I've got an array of numbers. I want to convert it into an array
> where each element is the rank of that element in the starting array (by
> rank I mean its position when sorted in decreasing order)
> For example, if my original array is
> [ 0.012, 0.08, 2, 0.5, 0.010, 0.03]
> my output array ought to look like this (starting at 1, rather than 0)
> [ 5, 3, 1, 2, 6, 4 ]
> meaning "the first element of the array is the 5th largest, the second is
> the 3rd largest, the third is the largest" and so on.
> The ordering can be done with argsort[::-1] (to get the decreasing order),
> but to get the final array, I can only think of clumsy ways of doing loops.
> Any ideas?
> Thanks!
> J

If you don't want to split ties nor handle NaNs:

>> (-a).argsort().argsort() + 1
   array([5, 3, 1, 2, 6, 4])

To handle ties you can use:

from scipy.stats import rankdata

To handle ties and NaNs, you can use the labeled array package, la:

>> import la
>> lar = la.larry([0.012, 0.08, 2, 0.5, 0.010, 0.03])
>> (-lar).ranking(norm='0,N-1').A + 1
   array([ 5.,  3.,  1.,  2.,  6.,  4.])


More information about the SciPy-User mailing list