Logical operations on arrays

Logical operations can be applied to arrays to test the array values against specific criteria. The following code tests if the values of the array are less than 2:

In [28]:
   # which items are less than 2?
   a = np.arange(5)
   a < 2

Out[28]:
   array([ True,  True, False, False, False], dtype=bool)

Note that this has resulted in an array of Boolean values. The value of each item in the array is the result of the logical operation on the respective array element.

It is worth pointing out that this does not work with more complicated expressions, such as this:

In [29]:
   # this is commented as it will cause an exception
   # print (a<2 or a>3)

This can be made to work by using parentheses around the logical conditions and using ...

Get Learning pandas now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.