Numpy 3D数组索引 [英] Numpy 3d array indexing
问题描述
在下面的示例中,我有一个3d numpy数组( n_samples x num_components x 2 ), n_samples = 5, num_components =7.
I have a 3d numpy array (n_samples x num_components x 2) in the example below n_samples = 5 and num_components = 7.
我还有另一个数组( indices ),它是每个形状为( n_samples ,)的样本的选定组件.
I have another array (indices) which is the selected component for each sample which is of shape (n_samples,).
我想从给定索引的数据数组中进行选择,以使结果数组为 n_samples x 2 .
I want to select from the data array given the indices so that the resulting array is n_samples x 2.
代码如下:
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?
例如,对于数据0,所选组件应为0,对于数据1,所选组件应为1.
For example for data 0, the selected component should be the 0th and for data 1 the selected component should be 1.
请注意,我无法在forano中使用任何循环,因为我在Theano中使用了它,因此解决方案应完全基于numpy.
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.
推荐答案
这是您要寻找的吗?
In [36]: data[np.arange(data.shape[0]),indices,:]
Out[36]:
array([[7, 4],
[7, 3],
[4, 5],
[8, 2],
[5, 8]])
这篇关于Numpy 3D数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!