【问题标题】:numpy "TypeError: ufunc 'bitwise_and' not supported for the input types" when using a dynamically created boolean mask使用动态创建的布尔掩码时,numpy“TypeError:输入类型不支持 ufunc 'bitwise_and'”
【发布时间】: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)

标签: python numpy


【解决方案1】:

&amp;precedence== 高,所以表达式

a == 2.0 & b

相同
a == (2.0 & b)

您收到错误是因为未为浮点标量和布尔数组定义按位 and

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

(a == 2.0) & b

【讨论】:

  • 谢谢。现在这很有意义!
  • 30 年后,PEMDAS 还在咬我。
【解决方案2】:

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

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

a = a.astype(int)
# working

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2018-03-09
    • 2018-07-25
    • 2020-07-21
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2020-02-16
    相关资源
    最近更新 更多