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

lin*_*cks 4 python numpy

在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'
Run Code Online (Sandbox Code Playgroud)

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

>>> c = a == 2.0
>>> c & b
array([False,  True, False], dtype=bool)
Run Code Online (Sandbox Code Playgroud)

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

>>> type(a == 2.0)
<type 'numpy.ndarray'>
>>> (a == 2.0).dtype
dtype('bool')
>>> type(c)
<type 'numpy.ndarray'>
>>> c.dtype
dtype('bool')
Run Code Online (Sandbox Code Playgroud)

为什么会有所不同?

War*_*ser 8

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

a == 2.0 & b
Run Code Online (Sandbox Code Playgroud)

是相同的

a == (2.0 & b)
Run Code Online (Sandbox Code Playgroud)

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

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

(a == 2.0) & b
Run Code Online (Sandbox Code Playgroud)


小智 5

你应该尝试将数组转换为 int

a = np.array([0,0,1])
# error bitwise

a = a.astype(int)
# working
Run Code Online (Sandbox Code Playgroud)