gpt4 book ai didi

python - `x[False]` 在 numpy 中做什么?

转载 作者:太空狗 更新时间:2023-10-29 20:23:41 25 4
gpt4 key购买 nike

假设我有一个数组 x = np.arange(6).reshape(3, 2)

x[False]x[np.asanyarray(False)] 是什么意思?两者都导致 array([], shape=(0, 3, 2), dtype=int64),这是意外的。

我希望得到一个 IndexError 因为掩码大小不正确,例如 x[np.ones((2, 2), dtype=np.bool)].

对于 x[True]x[np.asanyarray(True)],这种行为一致的,因为两者都会导致额外的维度:array([[[0, 1], [2, 3], [4, 5]]])

我正在使用 numpy 1.13.1。最近似乎行为发生了变化,因此虽然很高兴获得旧版本的答案,但请在答案中提及您的版本。

编辑

为了完整起见,我提交了 https://github.com/numpy/numpy/issues/9515基于对这个问题的评论。

编辑 2

然后几乎立即关闭了它。

最佳答案

技术上没有要求掩码的维数与您用它索引的数组的维数相匹配。 (在以前的版本中,限制甚至更少,并且您可以摆脱一些极端的形状不匹配。)

docs将 bool 索引描述为

A single boolean index array is practically identical to x[obj.nonzero()] where, as described above, obj.nonzero() returns a tuple (of length obj.ndim) of integer index arrays showing the True elements of obj.

但是 nonzero 对于 0 维输入来说很奇怪,所以这种情况是“几乎相同”结果不相同的一种方式:

the nonzero equivalence for Boolean arrays does not hold for zero dimensional boolean arrays.

NumPy 有一个 0 维 bool 索引的特例,其动机是希望具有以下行为:

In [3]: numpy.array(3)[True]
Out[3]: array([3])

In [4]: numpy.array(3)[False]
Out[4]: array([], dtype=int64)

我会引用 comment在处理 0 维 bool 索引的源代码中:

if (PyArray_NDIM(arr) == 0) {
/*
* This can actually be well defined. A new axis is added,
* but at the same time no axis is "used". So if we have True,
* we add a new axis (a bit like with np.newaxis). If it is
* False, we add a new axis, but this axis has 0 entries.
*/

虽然这主要用于 0 维数组的 0 维索引,但它也适用于使用 bool 值索引多维数组。因此,

x[True]

等同于x[np.newaxis],产生一个新的长度为1的轴在前面的结果,并且

x[False]

在长度为 0 之前生成一个新轴的结果,不选择任何元素。

关于python - `x[False]` 在 numpy 中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45493270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com