Suppose you have an unsorted list and you sort it using np.sort
. Is there a way to get the indices of the sorted list from the original list using numpy?
Asked
Active
Viewed 106 times
1

lord12
- 2,837
- 9
- 35
- 47
-
2Are you looking for `argsort`, as in [this question](http://stackoverflow.com/questions/7341557/get-original-indices-of-a-sorted-numpy-array)? – DSM Mar 31 '13 at 19:48
-
1Would you accept an answer using python builtin `sorted`? `args = [9, 7, 5, 3, 1, 8, 6, 4, 2, 0]; print sorted((value, index) for index, value in enumerate(args))` – hughdbrown Mar 31 '13 at 19:54
-
@DSM I used argsort(). Thanks – lord12 Mar 31 '13 at 20:05
-
@lord12 If this question is answered to your satisfaction, you should accept an answer by clicking the green checkmark next to the best answer, as per [faq]. – askewchan Apr 01 '13 at 14:46
1 Answers
1
The easiest way is to augment the array with the position indices and then sort the 2-D array. That gives you both the sorted data and its original position indicies at the same time.
If you only want the indicies (not the sorted data), the use argsort:
>>> from numpy import array
>>> arr = array([10, 5, 80, 20, 70, 18])
>>> arr.argsort()
array([1, 0, 5, 3, 4, 2])

Raymond Hettinger
- 216,523
- 63
- 388
- 485