hanuta98
hanuta98

Reputation: 89

Recover permutation of a vector

In numpy, how do I efficiently recover the permutation applied by a sorting algorithm to a vector such that at at every index in the resulting vector I have an integer representing the index the item in the orginal vector gets projected to after the application of the sorting algorithm.

>>>import numpy as np

>>> my_vector = np.random.random_integers(1,50,size=5)
>>> my_vector
array([23, 20, 33, 38, 27])

>>> my_v_sorted = np.sort(my_vector)
>>> my_v_sorted
array([20, 23, 27, 33, 38])

>>> what_i_want = np.array([1,0,4,2,3])

I want regardless of whether I actually need to sort to do this, I just want to mapping of the entries of my vector to the resulting indexes in the sorted vector, cheers!

Upvotes: 2

Views: 296

Answers (1)

James Carter
James Carter

Reputation: 833

You can use np.argsort()

import numpy as np

my_vector = np.array([23, 20, 33, 38, 27])

my_v_sorted = np.sort(my_vector)

what_i_want = np.argsort(my_vector)

This gives you the following output

>>> my_v_sorted
>>> array([20, 23, 27, 33, 38])

>>> what_i_want
>>> array([1, 0, 4, 2, 3])

Upvotes: 3

Related Questions