2

I have a vector withs 0s and 1s. I want to have a new vector with rearranged values, whereas I have another vector with a mapping rule:

Example:

input: 1,0,0,1
rule: 0,3,2,1
after mapping:1,1,0,0

The mapping vector determines for each index at which index in the new vector the value can be found.

How do I do that?

user1406177
  • 1,328
  • 2
  • 22
  • 36

1 Answers1

0

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.

Community
  • 1
  • 1