Indexing, Boolean Masks and Axes
Select data with slicing and boolean masks, aggregate along rows or columns with the axis argument, and understand the broadcasting rules that align arrays.
Welcome back!
Step 1 of 13Learn
Slicing arrays
NumPy indexing extends Python's list slicing to multiple dimensions. With a 1-D array:
a = np.array([10, 20, 30, 40, 50])
a[0] # 10
a[-1] # 50
a[1:4] # [20 30 40] start included, stop excluded
a[::2] # [10 30 50] every second elementWith a 2-D array, you give one index or slice per axis, separated by a comma: rows first, then columns.
m = np.array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
m[1, 2] # 7 row 1, column 2
m[0] # [1 2 3 4] the whole first row
m[:, 1] # [ 2 6 10] every row, column 1
m[:2, 2:] # [[3 4] [7 8]] first two rows, last two columnsOne important difference from lists: a slice of a NumPy array is a view, not a copy. Changing sub = m[:2, :2] and then sub[0, 0] = 99 also changes m. This saves memory on large arrays but surprises people who expect independent data. Use .copy() when you need one: sub = m[:2, :2].copy().
Step 2 of 13Practice · Match the pairs
Using the 3 × 4 array m above, match each expression to its result.
Tap an answer, then tap the place where it belongs (or drag it there).
m[2, 0]m[:, 3]m[1]m[1:, :2]
Step 3 of 13Learn
Boolean masks: filtering without loops
Comparing an array with a value produces an array of booleans, called a mask:
temps = np.array([18, 25, 31, 22, 35, 28])
temps > 27 # [False False True False True True]Using a mask as an index keeps only the elements where it's True:
temps[temps > 27] # [31 35 28]Masks combine with & (and), | (or) and ~ (not), and each condition must be wrapped in parentheses, because these operators bind more tightly than comparisons:
temps[(temps > 20) & (temps < 30)] # [25 22 28]Writing temps > 20 and temps < 30 raises "The truth value of an array with more than one element is ambiguous". Python's and needs a single True or False, but an array holds many.
Masks are also handy for counting and replacing. Since True counts as 1:
(temps > 27).sum() # 3 hot days
(temps > 27).mean() # 0.5, the share of hot days
np.where(temps > 27, "hot", "ok") # label each dayThe same masking logic powers pandas filtering, which you'll use constantly in the next module.
Step 4 of 13Practice · Spot the mistake
Each line is meant to select readings between 10 and 20 (inclusive) from a NumPy array r. Click the lines that are wrong.
Step 5 of 13Practice · Work it out
For temps = np.array([18, 25, 31, 22, 35, 28]), what does (temps >= 25).mean() return? Give the answer as a decimal.
Step 6 of 13Learn
Aggregating along an axis
Aggregation functions such as sum, mean, min, max and std collapse values into summaries. On a 2-D array, the axis argument says which direction to collapse:
sales = np.array([[10, 20, 30], # store 0: Mon, Tue, Wed
[ 5, 15, 25]]) # store 1
sales.sum() # 105 everything
sales.sum(axis=0) # [15 35 55] down the rows: one total per column (day)
sales.sum(axis=1) # [60 45] across the columns: one total per row (store)A reliable way to remember it: the axis you name is the one that disappears. The shape is (2, 3). Summing over axis 0 removes the 2, leaving 3 values; summing over axis 1 removes the 3, leaving 2 values.
pandas uses the same convention: df.mean() averages each column (axis 0, the default), and df.mean(axis=1) averages across each row.
A statistics detail that trips people up: NumPy's std divides by n by default (the population standard deviation, ddof=0), while pandas' .std() divides by n − 1 (the sample standard deviation, ddof=1). On the same data they give slightly different answers. Pass ddof explicitly when it matters.
Step 7 of 13Practice · Code challenge · Python
Implement axis-0 averaging in plain Python. Write column_means(rows) where rows is a list of equal-length lists (a 2-D table). Return a list with the mean of each column, rounded to 2 decimal places, like NumPy's arr.mean(axis=0).
column_means([[10, 20, 30], [5, 15, 25]])column_means([[1, 2], [3, 4], [5, 7]])column_means([[4, 8, 15, 16]])
Step 8 of 13Learn
Broadcasting
What happens when you combine arrays of different shapes? NumPy broadcasts the smaller one across the larger, as long as the shapes are compatible. You've used the simplest case already: prices * 1.08 broadcasts a single number to every element.
It works between arrays too. Suppose each row is a store and each column a day, and you want each value as a share of its day's total:
sales = np.array([[10, 20, 30],
[ 5, 15, 25]]) # shape (2, 3)
day_totals = sales.sum(axis=0) # shape (3,) -> [15 35 55]
shares = sales / day_totals # (2, 3) / (3,) -> each row divided element-wiseThe rule: compare shapes from the right. Two dimensions are compatible if they're equal or one of them is 1 (a missing dimension counts as 1). Then the size-1 dimension is stretched to match.
(2, 3)with(3,): compatible; the row of 3 is reused for both rows.(2, 3)with(2,): not compatible, since 3 and 2 differ. To divide each row by its row total, reshape the totals to a column:sales / sales.sum(axis=1).reshape(2, 1), shape(2, 1), or usekeepdims=True.
Broadcasting avoids copying data and lets you write normalization, centering and scaling in one line. When you get "operands could not be broadcast together", print both shapes and compare them from the right.
Step 9 of 13Practice · Sort into groups
Which shape pairs can be broadcast together?
Tap an item, then tap its group (or drag it there).
Step 10 of 13Learn
Fancy indexing and sorting
Besides slices and masks, NumPy lets you index with a list or array of positions, called fancy indexing:
a = np.array([10, 20, 30, 40, 50])
a[[0, 3, 4]] # [10 40 50]
a[[4, 0]] # [50 10] any order, repeats allowedSorting returns a sorted copy with np.sort(a), but often you want the positions that would sort the array, so you can reorder other, related arrays the same way. That's argsort:
names = np.array(["Harbor", "Market", "Park"])
bikes = np.array([14, 9, 21])
order = np.argsort(bikes)[::-1] # positions from highest to lowest
names[order] # ['Park' 'Harbor' 'Market']Related helpers: np.argmax(bikes) gives the position of the largest value (2 here), np.unique(values, return_counts=True) gives distinct values and their counts, and np.cumsum gives running totals.
These operations are the building blocks of many higher-level tools. pandas' sort_values, nlargest and value_counts are, underneath, versions of argsort, fancy indexing and unique counting, with labels attached.
Step 11 of 13Note
Step 12 of 13Practice · Work it out
For bikes = np.array([14, 9, 21, 9, 30]), what does np.argmax(bikes) return?
Step 13 of 13Practice · True or false
Taking a slice of a NumPy array, such as b = a[2:5], creates an independent copy, so changing b never affects a.
Lesson complete!