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.
CodePudding user response:
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)