O'Reilly logo

Learning pandas by Michael Heydt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required