Boolean operators with NumPy
Before, the operational operators like <
and >=
worked with NumPy arrays out of the box. Unfortunately, this is not true for the boolean operators and
, or
, and not
.
To use these operators with NumPy, you will need np.logical_and()
, np.logical_or()
and np.logical_not()
. Here's an example on the my_house
and your_house
arrays from before to give you an idea:
np.logical_and(my_house > 13,
your_house < 15)
This is a part of the course
“Intermediate Python”
Exercise instructions
- Generate boolean arrays that answer the following questions:
- Which areas in
my_house
are greater than18.5
or smaller than10
? - Which areas are smaller than
11
in bothmy_house
andyour_house
? Make sure to wrap both commands inprint()
statement, so that you can inspect the output.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create arrays
import numpy as np
my_house = np.array([18.0, 20.0, 10.75, 9.50])
your_house = np.array([14.0, 24.0, 14.25, 9.0])
# my_house greater than 18.5 or smaller than 10
# Both my_house and your_house smaller than 11