numpy抛出异常中的逻辑索引

2024-10-02 14:19:16 发布

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

我试图编写一些代码,使用逻辑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是否有真正的元素。为什么会这样,还有更好的方法吗?在


Tags: 代码importnumpyasnp数组逻辑bool
1条回答
网友
1楼 · 发布于 2024-10-02 14:19:16

据我所知,numpy将把你的2d逻辑索引转换成实际的索引向量:arr[[True,False],[False,True]]将变成{}形状为ndarray(2,2)。但是,在上一个例子中,第二个索引数组是full False,因此它对应于长度为0的索引数组。它与另一个完整的True索引向量配对,对应于长度为4的索引数组。在

来自the numpy manual

If the index arrays do not have the same shape, there is an attempt to broadcast them to the same shape. If they cannot be broadcast to the same shape, an exception is raised:

在您的情况下,错误正是由于以下原因造成的:

                                     -
IndexError                                Traceback (most recent call last)
<ipython-input-1411-28e41e233472> in <module>()
  > 1 unCov[colCov,rowCov]

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (4,) (0,)

另一方面,如果索引数组在任何给定维度上为空,MATLAB会自动返回一个空数组。在


这实际上突出了MATLAB和numpy中逻辑索引之间的根本区别。在MATLAB中,下标索引中的向量总是切分出一个子数组。也就是说,两者都是

^{pr2}$

以及

arr([true,true],[true,true])

将返回矩阵arr2 x 2子矩阵。如果逻辑索引向量比数组的给定维数短,则假定缺少的索引元素是false。有趣的事实:只要多余的元素都是false,索引向量也可以比给定维长。所以以上也相当于

arr([true,true,false,false],[true,true])

以及

arr([true,true,false,false,false,false,false],[true,true])

对于4 x 4数组(为了参数)。在

然而,在numpy中,以这种方式使用布尔值numpyarrays建立索引将试图提取一个向量。此外,布尔索引向量的长度应该与它们索引到的维度相同。在您的4 x 4示例中

unCov[np.array([True,True]),np.array([True,True])]

以及

unCov[np.array([True,True,False,False,False]),np.array([True,True,False,False,False])]

两者都返回两个第一对角线元素,因此不是子矩阵而是向量。此外,他们也给出了不那么鼓舞人心的警告

/usr/bin/ipython:1: VisibleDeprecationWarning: boolean index did not match indexed array along dimension 0; dimension is 4 but corresponding boolean dimension is 5

因此,在numpy中,逻辑索引向量的长度应该与ndarray的相应维度相同。然后我在上面写的是正确的:逻辑值被转换成索引,结果应该是一个向量。这个向量的长度是每个索引向量中True个元素的数量,所以如果你的布尔索引向量有不同数量的True元素,那么引用就没有意义了,你就会得到错误。在

相关问题 更多 >