简体   繁体   English

如何在numpy中获取两个索引数组之间的矩阵元素?

[英]How in numpy get elements of matrix between two indices arrays?

Let's say I have a matrix: 假设我有一个矩阵:

>> a = np.arange(25).reshape(5, 5)`
>> a
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

and two vectors of indices that define a span of matrix elements that I want to extract: 和两个索引向量,用于定义我想要提取的矩阵元素的范围:

>> indices1 = np.array([0, 1, 1, 0, 0])
>> indices2 = np.array([2, 3, 3, 2, 2])

As you can see, difference between each corresponding index is equal to 2. 如您所见,每个相应索引之间的差异等于2。

I would like to do sth like this extract a part of the matrix: 我想做这样的提取矩阵的一部分:

>> submatrix = a[indices1:indices2, :]

so that the result would be 2x5 matrix: 这样结果就是2x5矩阵:

>> submatrix
[[ 0  6  7  3  4],
 [ 5 11 12  8  9]]

For all I know, numpy allows to provide indices as a boundaries, but does not allow to provide arrays, only integers, eg a[0:2] . 据我所知,numpy允许提供索引作为边界,但不允许提供数组,只允许整数,例如a[0:2]

Note what I want to subtract is not a submatrix: 注意我想要减去的不是子矩阵:

在此输入图像描述

Do you know of some other way of indexing a numpy matrix so that it is possible to provide arrays defining spans? 您是否知道索引numpy矩阵的其他方法,以便可以提供定义跨度的数组? For now I managed to do it only with for loops. 现在我设法只使用for循环。

For reference, the most obvious loop (still took several experimental steps): 作为参考,最明显的循环(仍然需要几个实验步骤):

In [87]: np.concatenate([a[i:j,n] for n,(i,j) in enumerate(zip(indices1,indices2))], ).reshape(-1,2).T   
Out[87]: 
array([[ 0,  6,  7,  3,  4],
       [ 5, 11, 12,  8,  9]])

Broadcasted indices taking advantage of the constant length: 广播指数利用恒定长度:

In [88]: indices1+np.arange(2)[:,None]                                                                   
Out[88]: 
array([[0, 1, 1, 0, 0],
       [1, 2, 2, 1, 1]])
In [89]: a[indices1+np.arange(2)[:,None],np.arange(5)]                                                   
Out[89]: 
array([[ 0,  6,  7,  3,  4],
       [ 5, 11, 12,  8,  9]])

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

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