Data Analysis · NumPy Foundations · lesson 3 of 12
Indexing and boolean masks
about 15 minutes · free · runs in your browser
Step 1 of 2
Selecting with a condition
Arrays slice like lists — a[1:4], a[-1], a[::2] all behave as you would
expect. What they add is boolean indexing: put a boolean array inside the brackets
and you get back only the elements where it was True.
a = np.array([3, 9, 1, 7, 5])
mask = a > 4 # array([False, True, False, True, True])
a[mask] # array([9, 7, 5])
a[a > 4] # the same thing, written the way people actually write it
Conditions combine with & (and), | (or) and ~ (not) — not the and,
or, not keywords, which cannot work element by element. Each condition needs its
own brackets:
a[(a > 2) & (a < 8)] # array([3, 7, 5])
Forgetting those brackets is the single most common NumPy error, because & binds
tighter than >.
Your turn: from scores, select the passing scores (50 or more) and the middling
ones (40 up to but not including 70).
You start from this, and edit it in the browser:
import numpy as np
scores = np.array([35, 68, 92, 44, 50, 77, 12])
# Set passing and middling.
Step 2 of 2
Replacing values with np.where
np.where(condition, if_true, if_false) builds a new array by choosing between two
values element by element:
a = np.array([-3, 5, -1, 8])
np.where(a < 0, 0, a) # array([0, 5, 0, 8]) — floor negatives at zero
It is the vectorised if. You can also assign through a mask, which changes the array
in place:
a[a < 0] = 0
Your turn: write clip_negatives(values) that returns a new array with every
negative replaced by zero, leaving the input untouched.
You start from this, and edit it in the browser:
import numpy as np
def clip_negatives(values):
# Return a new array with negatives replaced by 0.
pass