Nooo
Nooo

Reputation: 1

Numpy: Turning an index array into an element array

Suppose I have an index array:

A = [1, 0, 3, 2, 0, 1]

for another array of values:

B = [21, 33, 10, 2]

Then I want a new array:

C = [B[A[0]], B[[A[1]], ..., B[A[[5]]] = [B[1], B[0], ..., B[1]] = [33, 21, ..., 21]

How does one do this with numpy arrays?

Upvotes: 0

Views: 32

Answers (1)

j1-lee
j1-lee

Reputation: 13929

You can apply numpy indexing when B is a numpy array:

import numpy as np

A = [1, 0, 3, 2, 0, 1]
B = np.array([21, 33, 10, 2])
output = B[A]
print(output) # [33 21  2 10 21 33]

Upvotes: 1

Related Questions