从技术上讲,没有要求掩码的维度与您索引的数组的维度相匹配. (在以前的版本中,限制更少,你可以摆脱一些极端的形状不匹配.)
docs将布尔索引描述为
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.
但非零对于0维输入来说很奇怪,所以这种情况是“几乎完全相同”的方式之一并不相同:
the nonzero equivalence for Boolean arrays does not hold for zero dimensional boolean arrays.
NumPy有一个0维布尔索引的特例,其动机是希望产生以下行为:
In [3]: numpy.array(3)[True]
Out[3]: array([3])
In [4]: numpy.array(3)[False]
Out[4]: array([], dtype=int64)
我将在源代码中引用处理0维布尔索引的comment:
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维索引,但它也适用于使用布尔值索引多维数组.从而,
x[True]
相当于x [np.newaxis],产生一个前面有一个新的长度为1的轴的结果,和
x[False]
在长度为0的前面生成一个新轴的结果,不选择任何元素.