linucks
linucks

Reputation: 815

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

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?

Upvotes: 39

Views: 107952

Answers (2)

Tuấn Anh Nguyễn
Tuấn Anh Nguyễn

Reputation: 51

you should try to convert your array to int

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

a = a.astype(int)
# working

Upvotes: 5

Warren Weckesser
Warren Weckesser

Reputation: 114871

& 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

Upvotes: 73

Related Questions