0

I have a numpy array and want to get both the sorted array and the correspoding indices from an original one. E.g.

arr = [2,1,3]
sorted_arr = [1,2,3]
sorted_indices = [1,0,2]

I know I can use np.sort(arr) and np.argsort(arr) to find them separately. But is there more efficient way that doesn't require sorting one array two times?

никта
  • 118
  • 3

3 Answers3

2

Yes, you can use argsort to get the sorted array.

import numpy as np
arr = np.array([2,1,3])
sorted_indices = np.argsort(arr)
sorted_arr = arr[sorted_indices]
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
2

You don't need to sort twice. If you need the indices that sort the array, you'll need np.argsort, but in order to sort the values in arr you only need to index with the result from np.argsort:

s = np.argsort(arr)
# array([1, 0, 2])
arr[s]
# array([1, 2, 3])
yatu
  • 86,083
  • 12
  • 84
  • 139
0

You could store the list elements and their indices in the same list using enumerate:

arr = [(x, i) for i,x in enumerate(arr)]

# Now you can use np.sort(arr) and unpack as necessary
np.sort(arr)
array([[0, 2],
       [1, 1],
       [2, 3]])

for x, idx in np.sort(arr):
    print(x, idx)
C.Nivs
  • 12,353
  • 2
  • 19
  • 44