Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy "TypeError: ufunc 'bitwise_and' not supported for the input types" when using a dynamically created boolean mask

Tags:

python

numpy

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?

like image 702
linucks Avatar asked Jun 02 '18 11:06

linucks


2 Answers

& 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
like image 153
Warren Weckesser Avatar answered Oct 12 '22 14:10

Warren Weckesser


you should try to convert your array to int

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

a = a.astype(int)
# working
like image 2
Tuấn Anh Nguyễn Avatar answered Oct 12 '22 16:10

Tuấn Anh Nguyễn