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

标签 python numpy matrix indexing matrix-indexing

假设我有一个矩阵:

>> 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 循环来完成它。

最佳答案

供引用,最明显的循环(还是做了几个实验步骤):

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

关于python - 如何在 numpy 中获取两个索引数组之间的矩阵元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56260854/

相关文章:

python - QLineEdit 未使用 setText 进行更新

python - 累积递归

python - Numpy 与 mldivide ,"\"matlab 运算符

python - Windows 上的错误 "Import Error: No module named numpy"

java - 计算Java中矩阵中未访问的单元格

python - 为什么在使用带有 asyncio 的协程的列表推导式时会得到不同的结果?

python - AffinityPropagation 聚类的输入格式

python - 如何在python中获取由三个坐标定义的平面的倾斜角度?

matrix - 贝叶斯网络的混淆矩阵

MATLAB : Dimension reduction