Boolean Masks

A comparison over an array gives an array of answers, and that array selects.

A comparison produces an array

scores > 85 is not one True or False. It is one per element, which is what makes the next line work.

import numpy as np

scores = np.array([92, 88, 79, 95])
print(scores > 85)

Index with the mask to select

Putting the mask inside the brackets keeps only the elements it marked. This is filtering, and it is the same idea pandas uses on whole tables.

import numpy as np

scores = np.array([92, 88, 79, 95])
print(scores[scores > 85])
print((scores > 85).sum())

Exercise

Try It Yourself

Write passing(scores, mark) that returns a list of the scores that are at least mark, using a mask rather than a loop.

Press Run to see output

Check Your Understanding