Book Image

Learning Pandas

By : Michael Heydt
Book Image

Learning Pandas

By: Michael Heydt

Overview of this book

Table of Contents (19 chapters)
Learning pandas
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 | instead of or:

In [30]:
   # less than 2 or greater than 3?
   (a<2) | (a>3)

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

NumPy provides the np.vectorize() function, which applies an expression...