numpy“TypeError: ufunc 'bitwise_and' 不支持输入类型"使用动态创建的布尔掩码时 [英] numpy "TypeError: ufunc 'bitwise_and' not supported for the input types" when using a dynamically created boolean mask

查看:136
本文介绍了numpy“TypeError: ufunc 'bitwise_and' 不支持输入类型"使用动态创建的布尔掩码时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 numpy 中,如果我有一个浮点数组,则动态创建一个布尔掩码,该数组等于特定值的位置,并使用布尔数组进行按位与运算,我得到一个错误:

<预><代码>>>>将 numpy 导入为 np>>>a = np.array([1.0, 2.0, 3.0])>>>a == 2.0 &乙回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:输入类型不支持 ufunc 'bitwise_and',并且无法根据转换规则 ''safe' 将输入安全地强制转换为任何受支持的类型

如果我将比较结果保存到一个变量并执行按位 AND 但是,它会起作用:

<预><代码>>>>c = a == 2.0>>>与乙数组([假,真,假],dtype=bool)

尽管在每种情况下创建的对象似乎都相同:

<预><代码>>>>类型(a == 2.0)<输入'numpy.ndarray'>>>>(a == 2.0).dtypedtype('bool')>>>类型(c)<输入'numpy.ndarray'>>>>数据类型dtype('bool')

为什么不同?

解决方案

& 有更高的 precedence==,所以表达式

a == 2.0 &乙

相同

a == (2.0 & b)

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

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

(a == 2.0) &乙

In numpy, if I have an array of floats, dynamically create a boolean mask of where this array equals a particular value and do a bitwise AND with a boolean array, I get an error:

>>> 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'

If I save the result of the comparison to a variable and carry out the bitwise AND however, it works:

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

The objects created seem the same in each case though:

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

Why the difference?

解决方案

& has higher precedence than ==, so the expression

a == 2.0 & b

is the same as

a == (2.0 & b)

You get the error because bitwise and is not defined for a floating point scalar and a boolean array.

Add parentheses to get what you expected:

(a == 2.0) & b

这篇关于numpy“TypeError: ufunc 'bitwise_and' 不支持输入类型"使用动态创建的布尔掩码时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆