1

Given an array, I would like to get an array holding the indices of the permutation that would result in the array being sorted. An example should make it clear: Input array:

[10, 50, 40, 20, 30]

should produce the following output:

[0, 3, 4, 2, 1]

because if I first take the 0th, then the 3rd, then the 4th, then the 2nd and then the 1st element of the list, I would get [10, 20, 30, 40, 50], which would be the sorted array.

Of course I could just code it in Python from scratch, but I wonder if there is a function for this in Python already.

  • 1
    Does this answer your question? [Equivalent of Numpy.argsort() in basic python?](https://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python) – Mr. T Feb 07 '22 at 12:28
  • not immediately, but following the links to other questions from there did in the end; thank you! – Karel Jilek Feb 07 '22 at 13:13

2 Answers2

1

Use NumPy argsort: that provides exactly what you need.

a = np.array([10, 50, 40, 20, 30])
np.argsort(a)

will result in

np.array([0, 3, 4, 2, 1])
rikyeah
  • 1,896
  • 4
  • 11
  • 21
0
a = [10, 50, 40, 20, 30]
ix = [a.index(v) for v in sorted(a)]

To my knowledge, there is no function for this. Just this half liner.

lmielke
  • 135
  • 8