0

I have a 2D array with indices refering to another array:

indexarray = np.array([[0,0,1,1],
                       [1,2,3,0]])

The array which these indices refer to is:

valuearray = np.array([8,7,6,5])

I would like to get an array with the numbers from valuearray in the shape of indexarray, each item in this array corresponds to the value in valuearray with the index on the same location in indexarray, ie:

targetarray = np.array([[8,8,7,7],
                        [7,6,5,8]])

How can I do this without iteration?


What I do now to achieve this is:

np.apply_along_axis(func1d = lambda row: valuearray[row],axis=0,arr = indexarray)

If there is a simpler way, I am interested.

2
  • 1
    targetarray = valuearray[indexarray.flatten()].reshape(indexarray.shape) Commented Dec 27, 2021 at 15:18
  • Feel free to add it is an answer if you want. Commented Dec 27, 2021 at 15:22

1 Answer 1

1

One way is to flatten the index array and get the values and reshape it back as follows.

targetarray = valuearray[indexarray.flatten()].reshape(indexarray.shape)
Sign up to request clarification or add additional context in comments.

2 Comments

Does the simpler valuearray[indexarray] work?
Oh yeah. It works without flattening too :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.