Boolean Masks
Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 14 of 60.
Which phones need charging? Compare an array with a number and every value answers True or False. That answer is a boolean mask:
Put the mask in square brackets to keep the True values, or sum it to count them:
levels = np.array([80, 15, 42, 9, 67])
low = levels < 20
print(levels[low])
print(low.sum())This prints:
[15 9]
2True counts as 1 and False as 0. Matches and counts, no loop.
Combine masks with & (both) or | (either), each comparison in parentheses: (levels > 30) & (levels < 70).
Challenge
EasyA courier app wants today's on-time deliveries: those taking from low to high minutes, both included. times is ready, and the program reads low and high. Print:
On time:the on-time times, in their original order.On time count:how many there are.Outside count:how many were faster thanlowor slower thanhigh.
For a window of 30 to 45 minutes:
On time: [34 41 38 31 44]
On time count: 5
Outside count: 7Try it yourself
import numpy as np
times = np.array([18, 34, 25, 41, 22, 29, 15, 38, 27, 31, 44, 20])
low = int(input())
high = int(input())
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature Grid3Array Math
Math on Whole ArraysSummary StatisticsStatistics by AxisBroadcastingBoolean MasksRecap: Exam Scores9Grouping and Cleaning
Counting ValuesGrouping DataSeveral SummariesMissing ValuesRecap: Survey ResultsPractice on your own: Online Python compiler