https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
If obj.ndim == x.ndim, x[obj] returns a 1-dimensional array filled with the elements of x corresponding to the True values of obj. The search order will be row-major, C-style. If obj has True values at entries that are outside of the bounds of x, then an index error will be raised. If obj is smaller than x it is identical to filling it with False.
我从 numpy 引用中读到我可以使用较小的 bool 数组索引较大的数组,其余条目将自动填充为 False。
Example : From an array, select all rows which sum up to less or equal two:
>>> x = np.array([[0, 1], [1, 1], [2, 2]])
>>> rowsum = x.sum(-1)
>>> x[rowsum <= 2, :]
array([[0, 1],[1, 1]])
But if rowsum would have two dimensions as well:
>>> rowsum = x.sum(-1, keepdims=True)
>>> rowsum.shape
(3, 1)
>>> x[rowsum <= 2, :] # fails
IndexError: too many indices
>>> x[rowsum <= 2]
array([0, 1])
The last one giving only the first elements because of the extra dimension.
但是这个例子根本不起作用,它说“IndexError: bool 索引与维度 1 上的索引数组不匹配;维度是 2 但相应的 bool 维度是 1”
最佳答案
从 Numpy 11 开始,它与新的默认行为不兼容:( boolean-indexing-changes ):
Boolean indexing changes.
...
...
Boolean indexes must match the dimension of the axis that they index.
...
内部已经优化,文档还没有....
关于Python 使用较小的 bool 数组索引 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47669683/