Python “numpy”;类型错误:ufunc';按位u和';“不支持输入类型”;使用动态创建的布尔掩码时

Python “numpy”;类型错误:ufunc';按位u和';“不支持输入类型”;使用动态创建的布尔掩码时,python,numpy,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 <mo

在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'
创建的对象在每种情况下看起来都是一样的:

>>> 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)
>>>(a==2.0).dtype
数据类型('bool')
>>>类型(c)
>>>c.D类型
数据类型('bool')
为什么不同?

&
的值高于
=
,因此表达式

a == 2.0 & b

a == (2.0 & b)
由于未为浮点标量和布尔数组定义按位
,因此会出现错误

添加括号以获得所需内容:

(a == 2.0) & b

请尝试
np.bitwise\u和(a==2.0,b)
谢谢。现在这很有道理!30年后,彭达斯还在咬我。
(a == 2.0) & b