Menu
CoddyTech

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:

Five battery levels 80, 15, 42, 9 and 67 as cells. The cells 15 and 9 are highlighted, and the mask below reads False, True, False, True, False

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]
2

True 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 icon

Challenge

Easy

A 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:

  1. On time: the on-time times, in their original order.
  2. On time count: how many there are.
  3. Outside count: how many were faster than low or slower than high.

For a window of 30 to 45 minutes:

On time: [34 41 38 31 44]
On time count: 5
Outside count: 7

Try 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler