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

2024-04-20 14:17:21 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个矩阵:

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

两个索引向量定义了我要提取的矩阵元素的范围:

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

如您所见,每个对应索引之间的差等于2。你知道吗

我想这样做提取矩阵的一部分:

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

结果是2x5矩阵:

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

据我所知,numpy允许提供索引作为边界,但不允许提供数组,只允许提供整数,例如a[0:2]。你知道吗

注意,我要减去的不是子矩阵:

enter image description here

你知道其他一些索引numpy矩阵的方法吗,这样就可以提供定义跨距的数组了?目前,我只能用For循环来实现它。你知道吗


Tags: numpy元素定义np矩阵整数数组array
1条回答
网友
1楼 · 发布于 2024-04-20 14:17:21

作为参考,最明显的循环(仍然采取了几个实验步骤):

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

利用恒定长度的广播索引:

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

相关问题 更多 >