Indexing, slicing and masks
Last updated
Most questions about data start with picking part of it: Tuesday's sales, the last three days, every day over 45 kg. In this lesson you'll pick parts of arrays by position, by slice and by condition. The last of those, the boolean mask, is how you'll filter data for the rest of the course.
By the end of this lesson you can
- Pick elements, rows, columns and blocks by position and slice
- Filter an array with a boolean mask
- Combine conditions with
&and|, and say whyandfails - Choose between two values with
np.where
Positions and slices
Slicing an array works like slicing a list or a string, with one addition: in 2-D you give the rows and the columns, separated by a comma. Step through the picture, then run the cells.
a = np.arange(0, 100, 10). Positions start at 0. a[3] is one number: 30.The rules, all from Python:
- Positions start at 0. Negative positions count from the end:
-1is the last. - A slice
start:stop:stepincludesstartand stops beforestop. Leave a part out to mean "from the beginning", "to the end" or "every one". - In 2-D,
g[rows, columns]. A bare:means "all of them", sog[:, 2]is a whole column andg[1, :], or justg[1], is a whole row.
Masks
Positions are useful when you know where things are. Usually you don't: you want "the days over 45 kg", wherever they are. That's a mask. Run the cells.
kilos > 45compares every element and gives an array ofTrueandFalse, the same shape. That's the mask.kilos[mask]keeps the elements where the mask isTrue:[51, 66, 59].- For two conditions, use
&(and) and|(or), with brackets round each condition. Without the brackets, Python would work out40 & kilosfirst. kilos[[0, 6]]picks by a list of positions: the first and last day. This is called fancy indexing.np.where(condition, a, b)givesawhere the condition is true andbwhere it isn't: a label for every day.
Try kilos[kilos < kilos.mean()] in a new cell: the days below the week's average.
Wrong way: and instead of &
In plain Python you write and. Try it on arrays.
The truth value of an array with more than one element is ambiguous. Python's and asks "is the left side true?", one yes or no for the whole thing. But kilos > 40 is seven answers, some True and some False, so there's no single answer, and NumPy refuses to guess.
& compares element by element instead, which is what you meant. Change and to & and run it again. The same goes for or (use |) and not (use ~). You'll see this error again in pandas, for the same reason.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- NumPy: Indexing on ndarrays: slices, boolean masks and integer-array indexing
- NumPy: numpy.where: one value where a condition holds, another where it doesn’t
- The Python Tutorial: Strings, slicing: the slice rules arrays share with Python