Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the Index of sorted elements in Python Array

I have seen answers to the question:
Is it possible to arrange a numpy array (or python list) by using the indexes of the elements in decreasing order? (eg. Finding the Index of N biggest elements in Python Array / List Efficiently)

A very concise answer seems to be (from above link):

L = array([4, 1, 0, 8, 5, 2])
sorted(range(len(L)), key=lambda i:L[i])

This gives the position (in the original array) of the sorted elements.

8 --> 3
5 --> 4
4 --> 0
2 --> 5
1 --> 1
0 --> 2

So the answer is:

[3, 4, 0, 5, 1, 2]

What I am after is the position (in the sorted array) of the elements:

L = array([4, 1, 0, 8, 5, 2])

8 --> 0
5 --> 1
4 --> 2
2 --> 3
1 --> 4
0 --> 5

So I want :

[2, 4, 5, 0, 1, 3] 

I realise I could take the answer from the first example, and use that to get what I want (with a bit more fiddling) but is there a short cut?

Efficiency is not a concern. I just need something that gives me the answer.

like image 961
RustyC Avatar asked Sep 20 '26 16:09

RustyC


1 Answers

EDIT when I first read the question, I thought you were looking for numpy.argsort.

Having read it again, I realized I misread.

scipy.stats.rankdata is what you're looking for (offset by 1, and reversed)

(scipy.stats.rankdata([4, 1, 0, 8, 5, 2])-1)[::-1]
=> array([ 2.,  4.,  5.,  0.,  1.,  3.])

(Original wrong answer, referring to argsort:)

from numpy import array, argsort
L = array([4, 1, 0, 8, 5, 2])
argsort(L)
=> array([2, 1, 5, 0, 4, 3])
like image 50
shx2 Avatar answered Sep 22 '26 06:09

shx2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!