When doing boolean array comparison, is there any advantage / convention to using & in place of * or | in place of +?  Are these always equivalent?
(if these are in the documentation, a link would probably be an acceptable answer, but my naive search for 'numpy ampersand' and 'numpy elementwise boolean comparison' didn't yield anything relevant)
In numpy & and | are equivalent to np.bitwise_and and np.bitwise_or. You can also use ^ for np.bitwise_xor. This is all documented in the Arithmetic and comparison operations section of the ndarray docs. There are also ufuncs for np.logical_and, np.logical_or and np.logical_xor.
If your arrays are all of dtype bool there shouldn't be any difference. I personally lean towards & and |, even though if you are not strict about the bool dtype it can get you in troubles like this:
In [30]: np.array(2) & np.array(1)
Out[30]: 0
In case someone wondered: the operations have the same speed and it therefore does not matter which one you choose.
In [1]: import numpy as np
In [2]: a = np.random.randn(1000)>0
In [3]: b = np.random.randn(1000)>0
In [4]: %timeit a*b
100000 loops, best of 3: 2.89 us per loop
In [5]: %timeit a&b
100000 loops, best of 3: 2.87 us per loop
In [6]: %timeit a+b
100000 loops, best of 3: 2.69 us per loop
In [7]: %timeit a|b
100000 loops, best of 3: 2.62 us per loop
As far as I am concerned, I use & and | to make explicit that I'm interested in a boolean operation (in case the reader forgot the dtype of the arrays in question).
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