Search code examples
pythonarraysnumpymatrix-indexingarray-broadcasting

Numpy 3d array indexing


I have a 3d numpy array (n_samples x num_components x 2) in the example below n_samples = 5 and num_components = 7.

I have another array (indices) which is the selected component for each sample which is of shape (n_samples,).

I want to select from the data array given the indices so that the resulting array is n_samples x 2.

The code is below:

import numpy as np
np.random.seed(77)
data=np.random.randint(low=0, high=10, size=(5, 7, 2))
indices = np.array([0, 1, 6, 4, 5])
#how can I select indices from the data array?

For example for data 0, the selected component should be the 0th and for data 1 the selected component should be 1.

Note that I can't use any for loops because I'm using it in Theano and the solution should be solely based on numpy.


Solution

  • Is this what you are looking for?

    In [36]: data[np.arange(data.shape[0]),indices,:]
    Out[36]: 
    array([[7, 4],
           [7, 3],
           [4, 5],
           [8, 2],
           [5, 8]])