Data Analysis with Python: From Raw Data to Real-World Insights
BOOK 2 · NUMPY · CHAPTER 3

Chapter 3 worked answers: Computing with NumPy

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-03-E01 · Name the reduction axis

Find one total per column and one total per row; name the retained axis meaning.

Reducing axis 0 removes rows; reducing axis 1 removes columns. The surviving dimensions retain their meaning.

visits=np.array([[10,14],[20,22],[30,36]])
columns=visits.sum(axis=0);rows=visits.sum(axis=1)
assert columns.tolist()==[60,72] and rows.tolist()==[24,42,66]
print(columns,rows)
[60 72] [24 42 66]

B2-03-E02 · Broadcast an adjustment

Add one offset per row without a loop; preserve shape (3,2).

A (3,1) offset has a length-one trailing dimension that broadcasts across the two columns.

a=np.array([[1,2],[3,4],[5,6]])
offset=np.array([10,20,30])
result=a+offset[:,None]
assert result.tolist()==[[11,12],[23,24],[35,36]]
print(result)
[[11 12]
 [23 24]
 [35 36]]

B2-03-E03 · Handle a numerical domain

Calculate logarithms only for positive entries and retain an explicit missing result for zero.

The domain decision is explicit and the zero is not silently replaced by a fabricated positive value.

a=np.array([0.,1.,4.,9.])
result=np.full(a.shape,np.nan)
mask=a>0;result[mask]=np.log(a[mask])
assert np.isnan(result[0]) and np.isclose(result[2],np.log(4))
print(result)
[       nan 0.         1.38629436 2.19722458]

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.

Teaching edition · verified experiments · PDF and EPUB editions not generated.