Finding The Index Of Sorted Elements In Python Array
Solution 1:
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])
Solution 2:
You can simply use your technique twice to get the indices in the sorted list:
A=[4, 1, 0, 8, 5, 2]
B=sorted(range(len(A)),key=lambda x:A[x],reverse=True)
C=sorted(range(len(A)),key=lambda x:B[x])
print C
prints
[2, 4, 5, 0, 1, 3]
Explanation
The idea is that the first iteration produces a list:
B = [3, 4, 0, 5, 1, 2]
giving the locations in the original list of the sorted sequence.
In other words, A[3]=8 is the largest element in the original list, A[4]=5 is the next largest, etc.
The second stage then sorts these indices in B back into the order 0,1,2,3,4,5 and produces C which contains the index in the list B.
It may help to think of B as sorting the list into descending order, and C as reversing the sort back into the original unsorted order, while keeping track of the indices in the sorted list.
Solution 3:
are you using numpy? if so, use numpy.argsort
import numpy as np
fakedata = np.array([40,20,60,50,10,20,80,30,50,40])
sorted_index = np.argsort(fakedata)
print(sorted_index)
print(fakedata[sorted_index])
[4157093826] # sorted index
[10202030404050506080] # values selected by the sorted index
Post a Comment for "Finding The Index Of Sorted Elements In Python Array"