使用动态创建的布尔掩码时,numpy“ TypeError:输入类型不支持ufunc'bitwise_and'”


问题内容

在numpy中,如果我有一个浮点数组,则动态创建一个布尔掩码,使该数组等于某个特定值,然后对布尔数组进行按位与运算,则会收到错误消息:

>>> import numpy as np
>>> a = np.array([1.0, 2.0, 3.0])
>>> a == 2.0 & b

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'

如果我将比较结果保存到变量中并按位执行AND,则可以:

>>> c = a == 2.0
>>> c & b
array([False,  True, False], dtype=bool)

但是,每种情况下创建的对象看起来都相同:

>>> type(a == 2.0)
<type 'numpy.ndarray'>
>>> (a == 2.0).dtype
dtype('bool')
>>> type(c)
<type 'numpy.ndarray'>
>>> c.dtype
dtype('bool')

为什么会有所不同?


问题答案:

&具有比更高的优先级==,因此表达式

a == 2.0 & b

是相同的

a == (2.0 & b)

因为and没有为浮点标量和布尔数组定义按位,所以会出现错误。

添加括号以获得您所期望的:

(a == 2.0) & b