【问题标题】:Don't understand the Numpy Boolean indexing documentation不理解 Numpy 布尔索引文档
【发布时间】:2022-01-17 09:09:32
【问题描述】:

我正在运行一个非常简单的示例 -

a = np.array([1,2,3,4,5])
mask= np.array([True, False])
a[mask]

这会产生IndexError: boolean index did not match indexed array along dimension 0; dimension is 5 but corresponding boolean dimension is 2

混淆源于我对Numpy doc这部分的理解(或缺乏理解):-

如果obj.ndim == x.ndim, x[obj] 返回一个由x 的元素填充的一维数组,对应于Trueobj 值。搜索顺序将是行优先的 C 样式。如果objTrue 值在x 的范围之外,则会引发索引错误。 如果obj 小于x,则等于用False 填充它。 (强调我的)

我认为mask 数组会转换为[True, False, False, False, False],但似乎情况并非如此。此外,amask 具有相同的 ndim 值,那么为什么错误消息会说 a 的维度为 5 但布尔维度为 2。

我错过了什么?如何解释文档?

【问题讨论】:

  • 错误中的 5 和 2 是沿维度 0 的维度长度。措辞可能会更好 tbh^^
  • 我想知道这是否是一个文档错误,没有跟上版本。 numpy 一直在清理这样的事情。我会确保布尔值匹配大小。
  • 您什么都没有,文档有误,错误消息使用 dimension 不一致。我不记得有什么时候这是正确的。
  • 我们需要搜索发行说明。
  • 请考虑在github of Numpy 上填写问题,以便帮助未来的用户(并可能解决这个可能的错误/措辞问题)。

标签: python numpy


【解决方案1】:

从 1.13 版开始,掩码大小必须匹配

https://numpy.org/doc/stable/release/1.13.0-notes.html#boolean-indexing-changes

Boolean indexing changes
Boolean array-likes (such as lists of python bools) are always treated as boolean indexes.

Boolean scalars (including python True) are legal boolean indexes and never treated as integers.

Boolean indexes must match the dimension of the axis that they index.

Boolean indexes used on the lhs of an assignment must match the dimensions of the rhs.

Boolean indexing into scalar arrays return a new 1-d array. This means that array(1)[array(True)] gives array([1]) and not the original array.

在 v 1.20 中,还有一个更小的修正,要求匹配形状和大小。

您引用的那行似乎是之前未强制执行大小匹配时遗留下来的。

大多数情况下,布尔掩码是通过对数组本身进行一些比较来构造的,因此大小匹配是自动的。人们通常不会构造短掩码——除非是错误地或测试文档。

【讨论】:

  • 如果您还提到相当不正确的错误消息会很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2020-03-25
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
相关资源
最近更新 更多