Python 使用较小的 bool 数组索引 numpy 数组

标签 python arrays numpy indexing

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”

如何让它工作?我使用的是 python 3.6.3 和 numpy 1.13.3。 enter image description here

最佳答案

从 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/

相关文章:

python - 要实现的场景,认为awk最适合这种情况

python - 如何使用 Mock 库模拟 Django ForeignKey 值?

arrays - Angular 6 : retrieve data from SelectionModel

c - 快速计算数组中较小/相等/较大元素的方法

python - 无法将类型 'Timestamp' 与类型 'int' 进行比较 - 减去数据集

python - 快速内插网格数据

python - numpy 例程和 ndarray 方法之间的区别?

python - 为什么连接两个数据帧时样本大小不同?

python - 如何使用 Beautifulsoup 获取这些 Json 代码?

javascript - 使用javascript更改html中每个元素的标签