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?

0

3 Answers 3

5

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])
Sign up to request clarification or add additional context in comments.

Comments

3

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]

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.