Monday, March 21, 2016

QuickTip: Numpy logical AND

Consider the following logical operations in Matlab or Octave

> a=[1, 2, 3]
> b=[2, 2, 2]
> a >= 2 & b<= 2
 0   1   1

which might be what you expect. The conditions are applied element by element, and the output is a boolean array the same size as the input vectors.

In numpy:

>>> a=np.array([1,2,3])
>>> b=np.array([2,2,2])
>>> a >= 2 & b <= 2  
Traceback (most recent call last):
  File "", line 1, in
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

However, to get the expected response (array of bools) stick the two parts in parenthesis:

>>> (a >= 2) & (b <= 2)
array([False,  True,  True], dtype=bool)

Note the usual "and" operator doesn't work:

>>> (a >= 2) and (b <= 2)
Traceback (most recent call last):
  File "", line 1, in
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

No comments:

Post a Comment