Module 4 · NumPy: Fast Maths on Arrays · Lesson 13 of 51

Indexing, slicing and boolean masks

Pick single values, rows, columns and blocks out of arrays, and filter with True/False masks: the idea behind every pandas filter.

In this lesson · about 35 minutes

  • Slice 1-D and 2-D arrays with start:stop:step
  • Filter values with a boolean mask, combining conditions with & and |
  • Know when a slice is a view and when to .copy()

1-D

a[0] first, a[-1] last, a[2:5] positions 2, 3, 4, a[::2] every second value, a[::-1] reversed.

2-D: rows, then columns

m[1, 2] is row 1, column 2. A colon means "all": m[0, :] is the whole first row, m[:, 0] the whole first column, m[:2, 1:3] a block (rows 0–1, columns 1–2).

Boolean masks

daily = np.array([1180, 1420, 990, 1610, 1530, 870])
mask = daily > 1500          # array([False, False, False, True, True, False])
daily[mask]                  # array([1610, 1530])
daily[(daily > 1000) & (daily < 1500)]

Combine conditions with & (and), | (or) and ~ (not), with brackets around each condition. Python's and/or don't work on arrays. mask.sum() counts the Trues; mask.mean() gives the share.

Loading a grid…

Masks on daily sales

Exercise

Quiet days

Using sales and days, set quiet to the names of days with sales under 1,000, and n_busy to the number of days with sales of 1,400 or more.

Exercise

Slice a block

sales has 3 branches (rows) × 4 quarters (columns). Set h2 to the second half of the year (Q3 and Q4) for all branches, and campus to the last row.

Check your understanding0 of 3 correct

Question 1

1.m[:, 0] selects…

Question 2

2.How do you combine two array conditions?

Question 3

3.(sales > 1000).mean() gives…

Quiz score: 0 of 3

Practice sets mastered: 0 of 1

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.