Selecting Rows with Masks
Introduction
Welcome back to Creating and Selecting from 2D NumPy Arrays. We’re at Lesson 6, where we’ll use familiar selection ideas to gather complete rows from a table. We’ll practice two approaches: listing row positions directly and building a Boolean mask from a column. We’ll also use that mask on a matching names array, so each selected score row stays connected to the right student.
Selecting Rows with an Index List
A row index list lets us choose specific rows and control their order. In the scores table, each row represents one student, and the three columns hold their math, reading, and science scores. The list [4, 0, 2] asks NumPy to gather rows at those positions.
The inner list contains row positions, not column positions. NumPy gathers rows 4, 0, and 2 in that order, including every column in each row. This is useful when we already know which records we want, such as when selecting specific students or delivery routes.
Index Lists Keep the 2D Shape
As in our earlier lessons, the shape tells us how many rows and columns a selection has. Here, three positions are listed, and each selected row keeps all three subject scores. We can print the selection with its shape to check that it is still a two-dimensional table.
The output contains three complete rows, followed by the shape:
The shape (3, 3) means three selected rows by three columns. Notice that the row order follows the index list: row 4 appears first, row 0 second, and row 2 third.
Building a Mask from a Column
An index list is handy when we choose positions ourselves. When we want rows that meet a condition, we can build a Boolean mask instead. As you may recall from earlier units, a comparison produces True or False values. Here, we compare the math score in each row, the first column, with 85.
The colon keeps every row, and 0 selects the first column. The comparison checks those five scores one by one, producing a one-dimensional mask with one value per row. A True marks a row to keep; a False marks a row to leave out.
A mask that selects rows must be 1D and have exactly one Boolean per row, so its length must equal scores.shape[0], which is 5 here. A mask of any other length raises an IndexError. A 2D mask with the same shape as the table, such as scores >= 85, works differently: it picks matching cells and returns them as a flat 1D array of values, not whole rows.

