1

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?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Ars ML
  • 49
  • 4

1 Answers1

2

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])
mozway
  • 194,879
  • 13
  • 39
  • 75