我试图编写一些代码,使用逻辑numpy数组索引一个更大的数组,类似于MATLAB如何允许使用逻辑数组索引数组。在
import numpy as np
m = 4
n = 4
unCov = np.random.randint(10, size = (m,n) )
rowCov = np.zeros( m, dtype = bool )
colCov = np.ones( n, dtype = bool )
>>> unCov[rowCov, rowCov]
[] # as expected
>>> unCov[colCov, colCov]
[0 8 3 3] # diagonal values of unCov, as expected
>>> unCov[rowCov, colCov]
ValueError: shape mismatch: objects cannot be broadcast to a single shape
对于最后一个计算,我期望得到一个空数组,类似于MATLAB返回的结果。我不想在索引之前检查rowCov/colCov是否有真正的元素。为什么会这样,还有更好的方法吗?在
据我所知,numpy将把你的2d逻辑索引转换成实际的索引向量:}形状为
arr[[True,False],[False,True]]
将变成{ndarray
的(2,2)
。但是,在上一个例子中,第二个索引数组是fullFalse
,因此它对应于长度为0的索引数组。它与另一个完整的True
索引向量配对,对应于长度为4的索引数组。在来自the numpy manual:
在您的情况下,错误正是由于以下原因造成的:
另一方面,如果索引数组在任何给定维度上为空,MATLAB会自动返回一个空数组。在
这实际上突出了MATLAB和numpy中逻辑索引之间的根本区别。在MATLAB中,下标索引中的向量总是切分出一个子数组。也就是说,两者都是
^{pr2}$以及
将返回矩阵
arr
的2 x 2
子矩阵。如果逻辑索引向量比数组的给定维数短,则假定缺少的索引元素是false
。有趣的事实:只要多余的元素都是false
,索引向量也可以比给定维长。所以以上也相当于以及
对于
4 x 4
数组(为了参数)。在然而,在numpy中,以这种方式使用布尔值numpy
arrays
建立索引将试图提取一个向量。此外,布尔索引向量的长度应该与它们索引到的维度相同。在您的4 x 4
示例中以及
两者都返回两个第一对角线元素,因此不是子矩阵而是向量。此外,他们也给出了不那么鼓舞人心的警告
因此,在numpy中,逻辑索引向量的长度应该与
ndarray
的相应维度相同。然后我在上面写的是正确的:逻辑值被转换成索引,结果应该是一个向量。这个向量的长度是每个索引向量中True
个元素的数量,所以如果你的布尔索引向量有不同数量的True
元素,那么引用就没有意义了,你就会得到错误。在相关问题 更多 >
编程相关推荐