Chapter 2 worked answers: NumPy Arrays and Selection
On this page
Compare your reasoning after an attempt. Different valid implementations are welcome when they preserve the observation set and the stated meaning.
B2-02-E01 · Select a rectangular block
Select rows 0–1 and columns 1–2. Preserve a two-dimensional result of shape (2,2).
Slices exclude their stop position; two row and two column positions remain.
a=np.arange(1,13).reshape(3,4)
selected=a[:2,1:3]
assert selected.tolist()==[[2,3],[6,7]]
print(selected)[[2 3]
[6 7]]
B2-02-E02 · Observe shared storage
Change b[0] to 99. Predict the new a, then make an independent copy for a second modification.
The first slice shares storage; the explicit copy does not.
a=np.array([2,4,6,8])
b=a[1:3]
b[0]=99
c=a[1:3].copy();c[0]=-1
assert a.tolist()==[2,99,6,8]
print(a)[ 2 99 6 8]
B2-02-E03 · Choose a boolean subset
Select values strictly above 7 and below 16; verify [8,12,15].
Parentheses isolate each comparison; & combines masks element by element.
a=np.array([3,8,12,15,20])
result=a[(a>7)&(a<16)]
assert result.tolist()==[8,12,15]
print(result)[ 8 12 15]
Return to practice
Change one supplied input, predict the effect and rerun your own implementation. Return to the exercise prompts to identify a task you can now explain independently.