Let's say a
is the original array and b
is the mapping rule. Since the mapping rule says "at which index in the new vector the value can be found", you need to compute a[c]
where c
is the inverse of the permutation b
. The computation of inverse permutation is addressed in detail elsewhere, so I'll pick one of solutions from there:
c = np.zeros(b.size, b.dtype)
c[b] = np.arange(b.size)
new_array = a[c]
Example: if a is [7, 8, 9]
and b is [1, 2, 0]
, this returns [9, 7, 8]
. Let's check:
- 7 went to position 1,
- 8 went to position 2,
- 9 went to position 0
The result is correct.
If you did a[b]
as suggested by Bort, the result would be [8, 9, 7]
, which is different. Indeed, in this version the entries of b
say where the numbers came from in the original array:
- 8 came from position 1
- 9 came from position 2
- 7 came from position 0
To muddle the matter, the example you gave is a permutation that is equal to its inverse, so the distinction is lost.