Masks, fancy indexing, reshape and axis
Change 60 to 70 in the mask and predict which scores survive before you run it. This is the shape of a real task: keep the exam results that pass, or the log lines whose response time is too slow.
You pick elements out of an array with indices, slices, boolean masks and lists of positions. Slices are views that share memory with the original, and reshape changes the shape without changing the numbers.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
From x = np.arange(1, 11), print only the even numbers using a mask (x % 2 == 0).
From grid = np.arange(9).reshape(3, 3), print the middle row, the last column, and the 2-by-2 block in the top left corner.
Given a = np.array([5, 1, 4]), make b = a[:2].copy(), set b[0] = 0, and show that a did not change.
For a = np.arange(10), use np.shares_memory to show that a[6:] is a view but a[a > 5] is a copy. Then use a slice to set the last four elements of a to 0 and print a.
Explain it without notes
What is the difference between a view and a copy? Which indexing methods give each?
How do you select the elements of an array that satisfy two conditions? Why not use and?
What does reshape(-1, 2) do, and when does reshape fail?
For a (2, 3) array, what are the shapes of sum(axis=0) and sum(axis=1) and why?
A function receives an array, sets arr[0] = 0 and the caller's data changes unexpectedly. Why, and how do you design around it?
Expected output
mask: [ True False True False True True]
passed: [72 90 68 85]
count passed: 4
between 50 and 80: [72 55 68]
fancy: [72 90 90 85]
floored: [72 55 90 50 68 85]
reshape 2x3: [[0, 1, 2], [3, 4, 5]]
reshape -1,2: [[0, 1], [2, 3], [4, 5]]
flatten: [0 1 2 3 4 5]
sum axis 0: [3 5 7] sum axis 1: [ 3 12]
ValueError: cannot reshape array of size 6 into shape (4,2)