I have two numpy arrays of the following shapes, and I need to extract values from a 3D array using stored indices from a 2D one:
- vals = (65, 65, 3500) This contains 3500 values that were calculated in a 65x65 grid, from which I need to extract values
- indices = (65, 65) This contains the indices of the minimum value of each of the 3500 of the previous array, of which I need to extract the values
The resulting array should again be (65, 65).
For example, if I have a value 1367 stored in indices[0,0], then I need vals[0,0,1367]. This needs to be repeated all the way to indices[64,64].
How can I do this sort of filter? I tried np.choose with reshaping vals to (3500, 65, 65), but that is limited to 32 columns and therefore crashed. Alternatively, how can I get the (65, 65) array of the minima of each set of 3500 values? Thanks
CodePudding user response:
this can be done using a meshgrid
import numpy as np
vals = np.random.rand(65,65,300)
indices = np.random.randint(0,299,[65,65])
mesh_grid = np.meshgrid(np.arange(indices .shape[0]),np.arange(indices .shape[1]),sparse=True)
output = vals[mesh_grid[0],mesh_grid[1],indices]
print(output.shape)
(65, 65)
CodePudding user response:
Numpy does not support integer arrays as indices to an array, so you have to create first a new 65x65 array and then fill it in a loop going over all the values in indices to extract the appropriate value from vals.
CodePudding user response:
val.reshape(65, -1)[np.repeat(np.arange(65), 65),
(indices 3500*np.arange(65)).ravel()]