Inverse array indexing in numpy

49 views Asked by At

I have an array and index list in numpy:

ar = np.array([4, 5, 3, -1, -1, 0, 1, 2])
indices = np.array([5, 6, 1, 2, 0, 7, 3, 4])

ar_permuted = ar[indices]
#ar_permuted = array([0, 1, 5, 3, 4, 2, -1, -1])

Now, given ar_permuted and indices, what is the most straightforward way to recover ar?

1

There are 1 answers

0
mozway On

Assuming all indices are present.

Using argsort:

out = ar_permuted[np.argsort(indices)]

Using indexing:

out = np.zeros(shape=len(ar_permuted), dtype=ar_permuted.dtype)
out[indices] = ar_permuted

Output:

array([ 4,  5,  3, -1, -1,  0,  1,  2])