【发布时间】:2018-06-02 11:10:00
【问题描述】:
在 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'
如果我将比较结果保存到变量并执行按位与,但是,它可以工作:
>>> 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')
为什么不一样?
【问题讨论】:
-
试试
np.bitwise_and(a==2.0,b)