[SciPy-User] Ranking a list of numbers

0 views
Skip to first unread message

Jose Gomez-Dans

unread,
Jun 3, 2010, 10:20:35 AM6/3/10
to SciPy Users List
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


Keith Goodman

unread,
Jun 3, 2010, 10:32:21 AM6/3/10
to SciPy Users List

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.])
_______________________________________________
SciPy-User mailing list
SciPy...@scipy.org
http://mail.scipy.org/mailman/listinfo/scipy-user

Keith Goodman

unread,
Jun 3, 2010, 10:36:10 AM6/3/10
to SciPy Users List

Oh, actually la has a pure array version:

>> a = np.array([0.012, 0.08, 2, 0.5, 0.010, 0.03])
>> from la.afunc import ranking
>> ranking(-a, norm='0,N-1') + 1

mdekauwe

unread,
Jun 3, 2010, 1:07:05 PM6/3/10
to scipy...@scipy.org

Hi,

Did you mean

import numpy as np
a = np.array([ 0.012, 0.08, 2, 0.5, 0.010, 0.03])
index = np.argsort(a)[::-1]
b = a[index]

print b
[ 2. 0.5 0.08 0.03 0.012 0.01 ]


Mart

> _______________________________________________
> SciPy-User mailing list
> SciPy...@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
>

--
View this message in context: http://old.nabble.com/Ranking-a-list-of-numbers-tp28768184p28770319.html
Sent from the Scipy-User mailing list archive at Nabble.com.

Reply all
Reply to author
Forward
0 new messages