10

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)

keflavich
  • 18,278
  • 20
  • 86
  • 118

2 Answers2

8

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
Jaime
  • 65,696
  • 17
  • 124
  • 159
6

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).

David Zwicker
  • 23,581
  • 6
  • 62
  • 77