简体   繁体   English

Numpy 3d数组索引

[英]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. 我在下面N_SAMPLES次 = 5和num_components = 7的示例的三维numpy的阵列(N_SAMPLES次X num_components×2)。

I have another array ( indices ) which is the selected component for each sample which is of shape ( n_samples ,). 我有另一个数组( 索引 ),它是每个样本的选定组件( n_samples ,)。

I want to select from the data array given the indices so that the resulting array is n_samples x 2 . 我想从给定索引的数据数组中进行选择,以便得到的数组是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. 例如,对于数据0,所选组件应为第0,对于数据1,所选组件应为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. 请注意,我不能使用任何for循环,因为我在Theano中使用它,解决方案应该完全基于numpy。

To get component #0, use 要获得组件#0,请使用

data[:, 0]

ie we get every entry on axis 0 (samples), and only entry #0 on axis 1 (components), and implicitly everything on the remaining axes. 即我们得到轴0(样本)上的每个条目,只有轴1(组件)上的条目#0,以及其余轴上的所有条目。

This can be easily generalized to 这可以很容易地推广到

data[:, indices]

to select all relevant components. 选择所有相关组件。


But what OP really wants is just the diagonal of this array, ie (data[0, indices[0]], (data[1, indices[1]]), ...) The diagonal of a high-dimensional array can be extracted using the diagonal function: 但OP真正想要的只是这个数组的对角线,即(data[0, indices[0]], (data[1, indices[1]]), ...)高维数组的对角线可以使用对diagonal函数提取:

>>> np.diagonal(data[:, indices])
array([[7, 7, 4, 8, 5],
       [4, 3, 5, 2, 8]])

(You may need to transpose the result.) (您可能需要转置结果。)

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]])

You have a variety of ways to do so, but this is my loop recommendation: 您有多种方法可以这样做,但这是我的循环建议:

selection = np.array([ datum[indices[k]] for k,datum in enumerate(data)])

The resulting array, selection , has the desired shape. 得到的阵列selection具有所需的形状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM