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
you should try to convert your array to int
a = np.array([0,0,1])
# error bitwise
a = a.astype(int)
# working
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With