23. NumPy — Exercises
These exercises practice every idea of the NumPy lesson. They use the course datasets: data/sensors.csv, data/sales.csv, data/houses.csv, data/products.csv and data/stores.csv, plus small matrices typed in from them.
How to work:
- Read the task and the expected output.
- Copy the setup block and the starter code into a script and replace each to-do comment with your code.
- Run the script and compare your output with the expected output.
- Stuck? Open one hint at a time. Open the solution only after a real attempt.
Each solution ends with assert checks. Use np.array_equal(a, b) for exact equality of arrays and np.allclose(a, b) or np.isclose(a, b) for floats.
Every exercise starts with this block. It imports NumPy and makes arrays print with at most 3 decimals.
import numpy as np
np.set_printoptions(precision=3, suppress=True)Warm-up
Section titled “Warm-up”M23-W01 · Describe a sales matrix
Section titled “M23-W01 · Describe a sales matrix”The matrix below is the real 2024 revenue (USD, rounded) of the three South stores by quarter. Create it as an array named south. Print its shape, its number of dimensions and elements, its dtype and its size in bytes. Then print the size in bytes of a float32 copy.
shape: (3, 4)ndim: 2 size: 12dtype: int64 nbytes: 96float32 nbytes: 48rows = [ [33792, 48602, 47361, 80978], # S04 Houston [32398, 31802, 38465, 57507], # S05 Atlanta [23145, 15046, 27471, 45699], # S06 Miami]# TODO: create the array south# TODO: print shape, ndim, size, dtype, nbytes and the float32 nbytesHint 1
np.array(rows) builds a 2-D array from a list of equal-length lists. Shape, dimensions, size, dtype and bytes are attributes, not methods: no parentheses.
Hint 2
The attributes are shape, ndim, size, dtype and nbytes. south.astype(np.float32) makes the float32 copy.
Solution
south = np.array([ [33792, 48602, 47361, 80978], # S04 Houston [32398, 31802, 38465, 57507], # S05 Atlanta [23145, 15046, 27471, 45699], # S06 Miami])print("shape:", south.shape)print("ndim:", south.ndim, "size:", south.size)print("dtype:", south.dtype, "nbytes:", south.nbytes)print("float32 nbytes:", south.astype(np.float32).nbytes)assert south.shape == (3, 4)assert south.nbytes == south.size * south.itemsize == 96assert south.astype(np.float32).nbytes == 48shape: (3, 4)ndim: 2 size: 12dtype: int64 nbytes: 96float32 nbytes: 48How it works:
np.array()reads the nested list. All values are whole numbers, so the dtype isint64.- 12 elements of 8 bytes each take 96 bytes.
nbytesis alwayssize * itemsize. astype(np.float32)returns a new array with 4-byte elements: 48 bytes.southitself is unchanged.
Alternative: pass the dtype when you create the array, np.array(rows, dtype=np.int32), to get 4-byte integers directly (48 bytes, values up to about 2.1 billion).
M23-W02 · Predict the output: lists and arrays
Section titled “M23-W02 · Predict the output: lists and arrays”Predict the output: write down what each line prints. Then run the code.
print([1, 2, 3] * 2)print(np.array([1, 2, 3]) * 2)print([1, 2] + [3, 4])print(np.array([1, 2]) + np.array([3, 4]))print(np.arange(3, 12, 3))print(np.linspace(0, 1, 5))print(np.zeros((2, 2), dtype=int))Acceptance criteria: write your prediction line by line, then run the code. Your prediction matches the Output in the solution.
Hint 1
For lists, * repeats and + joins. For arrays, both operators work element by element.
Hint 2
np.arange stops before the stop value, like range(). np.linspace(0, 1, 5) includes both ends and splits the range into 4 equal steps.
Solution
print([1, 2, 3] * 2)print(np.array([1, 2, 3]) * 2)print([1, 2] + [3, 4])print(np.array([1, 2]) + np.array([3, 4]))print(np.arange(3, 12, 3))print(np.linspace(0, 1, 5))print(np.zeros((2, 2), dtype=int))assert len([1, 2, 3] * 2) == 6assert np.array_equal(np.arange(3, 12, 3), [3, 6, 9])assert np.allclose(np.diff(np.linspace(0, 1, 5)), 0.25)[1, 2, 3, 1, 2, 3][2 4 6][1, 2, 3, 4][4 6][3 6 9][0. 0.25 0.5 0.75 1. ][[0 0] [0 0]]How it works:
- A list times 2 is the list twice: 6 items. An array times 2 doubles each element.
- Two lists joined with
+give one longer list. Two arrays added with+give their element-wise sum. np.arange(3, 12, 3)gives 3, 6, 9; 12 is excluded.np.linspace(0, 1, 5)gives 5 points with a step of 0.25, printed as floats.dtype=intmakes integer zeros, so they print without a decimal point.
M23-W03 · Fix the bug: units that wrap around
Section titled “M23-W03 · Fix the bug: units that wrap around”Fix the bug: a forecast script stores the daily units of three products as int8 to save memory, then doubles them for a promotion day. The forecast shows negative units. Fix the code so that the forecast is correct, and keep the stored array as int8.
int8 [240 190 220] int64units = np.array([120, 95, 110], dtype=np.int8)forecast = units * 2 # BUG: negative numbersprint(units.dtype, forecast, forecast.dtype)# TODO: fix the forecastHint 1
Print np.iinfo(np.int8). What is the largest value that the dtype can hold, and what is 120 × 2?
Hint 2
Convert to a wider integer dtype before you multiply. The result then has the wider dtype.
Solution
units = np.array([120, 95, 110], dtype=np.int8)forecast = units.astype(np.int64) * 2print(units.dtype, forecast, forecast.dtype)assert units.dtype == np.int8assert np.array_equal(forecast, [240, 190, 220])assert (forecast > 0).all()int8 [240 190 220] int64How it works:
int8holds −128 to 127. 240 does not fit, so the buggy line wrapped it around by 256 to −16, with no error.astype(np.int64)makes a wider copy. The multiplication then runs inint64, where 240 fits.- The stored
unitsarray keeps its 1-byte dtype; only the result is wider.
Alternative: np.multiply(units, 2, dtype=np.int64) computes in int64 without an explicit copy of the input. int16 (up to 32,767) would also be enough here.
M23-W04 · Slice the South matrix
Section titled “M23-W04 · Slice the South matrix”Use the south matrix of M23-W01 (rows S04, S05, S06; columns Q1 to Q4). With one index or slice expression each, print: the Q2 and Q3 revenue of S05; the Q4 column; the first half-year of the last two stores; every second quarter of S04 (Q1 and Q3).
[31802 38465][80978 57507 45699][[32398 31802] [23145 15046]][33792 47361]south = np.array([ [33792, 48602, 47361, 80978], [32398, 31802, 38465, 57507], [23145, 15046, 27471, 45699],])# TODO: S05 Q2-Q3, the Q4 column, the last two stores in Q1-Q2, S04 Q1 and Q3Hint 1
Write [rows, columns]. Row 1 is S05. Columns 1 and 2 are Q2 and Q3, which is the slice 1:3.
Hint 2
: alone means “all”. A step goes after a second colon: ::2 takes every second element.
Solution
south = np.array([ [33792, 48602, 47361, 80978], [32398, 31802, 38465, 57507], [23145, 15046, 27471, 45699],])s05_mid = south[1, 1:3]q4 = south[:, 3]last_two_h1 = south[1:, :2]s04_odd = south[0, ::2]print(s05_mid)print(q4)print(last_two_h1)print(s04_odd)assert np.array_equal(s05_mid, [31802, 38465])assert q4.shape == (3,) and q4.sum() == 184184assert last_two_h1.shape == (2, 2)assert np.array_equal(s04_odd, [33792, 47361])[31802 38465][80978 57507 45699][[32398 31802] [23145 15046]][33792 47361]How it works:
south[1, 1:3]takes row 1 and columns 1 up to (not including) 3.south[:, 3]takes column 3 of every row. One integer index removes that axis, so the result is 1-D.south[1:, :2]keeps both axes, because both are slices: shape(2, 2).south[0, ::2]starts at column 0 and takes every second column.
Alternative: south[:, -1] also selects the last column, and keeps working if you later add more quarters.
M23-W05 · Predict the output: view or copy
Section titled “M23-W05 · Predict the output: view or copy”Predict the output: three arrays are taken from temps in three ways, and each one gets a new first element. Which changes reach temps?
temps = np.array([20.21, 22.3, 19.4, 24.52])a = temps[1:3]b = temps[temps > 21]c = temps[[0, 3]]a[0] = 0.0b[0] = 0.0c[0] = 0.0print(temps)print(np.shares_memory(a, temps), np.shares_memory(b, temps))print(np.shares_memory(c, temps))Acceptance criteria: write the three lines that you expect, then run the code. Your prediction matches the Output in the solution.
Hint 1
Only one of the three ways gives a view. Which kind of index returns a view?
Hint 2
temps[1:3] starts at position 1, so a[0] is temps[1].
Solution
temps = np.array([20.21, 22.3, 19.4, 24.52])a = temps[1:3]b = temps[temps > 21]c = temps[[0, 3]]a[0] = 0.0b[0] = 0.0c[0] = 0.0print(temps)print(np.shares_memory(a, temps), np.shares_memory(b, temps))print(np.shares_memory(c, temps))assert temps[1] == 0.0assert temps[0] == 20.21 and temps[3] == 24.52[20.21 0. 19.4 24.52]True FalseFalseHow it works:
ais a basic slice, so it is a view.a[0] = 0.0writes intotemps[1].bcomes from a boolean mask, so it is a copy of[22.3, 24.52]. Changing it does not touchtemps.ccomes from fancy indexing, which also copies.np.shares_memoryconfirms it: onlyashares memory withtemps.
M23-W06 · Count the dry readings
Section titled “M23-W06 · Count the dry readings”Load temperature_c and humidity_pct (columns 2 and 3) of data/sensors.csv. Count the readings with humidity below 45%, print their share of all 8,064 rows with 4 decimals, and print the mean temperature of those dry readings and of all readings (ignore missing values).
dry readings: 69share: 0.0086mean temperature when dry: 27.37 °Cmean temperature overall: 24.06 °Cdata = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=(2, 3))temperature = data[:, 0]humidity = data[:, 1]# TODO: build the mask, count, share, two mean temperaturesHint 1
humidity < 45 is a boolean array. Its sum() counts the True values and its mean() gives their share.
Hint 2
temperature[dry] keeps the temperatures of the dry rows. Use np.nanmean because some temperatures are missing.
Solution
data = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=(2, 3))temperature = data[:, 0]humidity = data[:, 1]dry = humidity < 45print("dry readings:", dry.sum())print(f"share: {dry.mean():.4f}")print(f"mean temperature when dry: {np.nanmean(temperature[dry]):.2f} °C")print(f"mean temperature overall: {np.nanmean(temperature):.2f} °C")assert dry.sum() == np.count_nonzero(humidity < 45)assert np.nanmean(temperature[dry]) > np.nanmean(temperature)dry readings: 69share: 0.0086mean temperature when dry: 27.37 °Cmean temperature overall: 24.06 °CHow it works:
humidity < 45compares every element and returns 8,064 booleans. Missing humidity values (NaN) compare asFalse, so they are not counted as dry.dry.mean()divides the count by all 8,064 rows.- The dry readings are much warmer than average. The data dictionary says why: humidity moves against temperature.
Alternative: np.count_nonzero(dry) counts the True values too, and reads well in code reviews.
M23-W07 · Vibration statistics with gaps
Section titled “M23-W07 · Vibration statistics with gaps”The vibration_mm_s column (column 4) of data/sensors.csv has blank cells. Print the number of missing values, the plain mean, the NaN-aware mean and median, and the share of valid readings at or above the warn limit of 4.5 mm/s.
missing: 30mean: nannanmean: 2.724, nanmedian: 2.40share >= 4.5: 0.0549 of 8034 valid readingsvibration = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=4)# TODO: missing count, mean, nanmean, nanmedian, share >= 4.5 among valid readingsHint 1
np.isnan(vibration) marks the gaps. The plain mean() returns nan when any value is missing.
Hint 2
For the share among valid readings, first keep the valid values: valid = vibration[~np.isnan(vibration)].
Solution
vibration = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=4)missing = np.isnan(vibration)valid = vibration[~missing]print("missing:", missing.sum())print("mean:", vibration.mean())print(f"nanmean: {np.nanmean(vibration):.3f}, nanmedian: {np.nanmedian(vibration):.2f}")print(f"share >= 4.5: {(valid >= 4.5).mean():.4f} of {valid.size} valid readings")assert missing.sum() == 30assert np.isclose(np.nanmean(vibration), valid.mean())missing: 30mean: nannanmean: 2.724, nanmedian: 2.40share >= 4.5: 0.0549 of 8034 valid readingsHow it works:
usecols=4loads one column as a 1-D array; blanks become NaN.- The plain mean is
nan: one gap spoils the result. nanmeanequals the mean of the valid values. The mean (2.72) is above the median (2.40) because a few large values (S4 wear and the spikes) pull the mean up.~missinginverts the mask, sovalidholds the 8,034 real readings.
Alternative: np.count_nonzero(valid >= 4.5) / valid.size computes the same share from a count.
Common trap: np.nanmean(vibration >= 4.5) gives a different, wrong share. NaN >= 4.5 is False, not NaN, so the 30 gaps count as “below the limit”. Filter first, as in the solution.
M23-W08 · Totals per store and per quarter
Section titled “M23-W08 · Totals per store and per quarter”For the south matrix, print the total per store, the total per quarter, the grand total and the best quarter of each store as a label ("Q1" to "Q4").
per store: [210733 160172 111361]per quarter: [ 89335 95450 113297 184184]total: 482266best quarter: ['Q4' 'Q4' 'Q4']south = np.array([ [33792, 48602, 47361, 80978], [32398, 31802, 38465, 57507], [23145, 15046, 27471, 45699],])quarters = np.array(["Q1", "Q2", "Q3", "Q4"])# TODO: totals per store (axis?), per quarter (axis?), grand total, best quarter labelsHint 1
The axis you name disappears. One total per store means that the quarter axis (axis 1) disappears.
Hint 2
south.argmax(axis=1) gives the column position of each store’s maximum. Index quarters with it.
Solution
south = np.array([ [33792, 48602, 47361, 80978], [32398, 31802, 38465, 57507], [23145, 15046, 27471, 45699],])quarters = np.array(["Q1", "Q2", "Q3", "Q4"])per_store = south.sum(axis=1)per_quarter = south.sum(axis=0)best = quarters[south.argmax(axis=1)]print("per store:", per_store)print("per quarter:", per_quarter)print("total:", south.sum())print("best quarter:", best)assert per_store.sum() == per_quarter.sum() == south.sum()assert per_store[0] == 210733assert best.tolist() == ["Q4", "Q4", "Q4"]per store: [210733 160172 111361]per quarter: [ 89335 95450 113297 184184]total: 482266best quarter: ['Q4' 'Q4' 'Q4']How it works:
sum(axis=1)collapses the quarters: one total per store, shape(3,).sum(axis=0)collapses the stores: one total per quarter, shape(4,).- Both totals add up to the grand total, a cheap self-check for any aggregation.
argmax(axis=1)returns positions, and fancy indexing turns them into labels.
M23-W09 · Reproducible sensor noise
Section titled “M23-W09 · Reproducible sensor noise”Simulate 5 readings of a sensor with mean 22.0 °C and standard deviation 0.5 °C, using a generator with seed 42. Create a second generator with the same seed and check that it gives the same 5 readings. Then use the first generator to pick 3 distinct stores out of S01 to S12 for a store audit.
[22.152 21.48 22.375 22.47 21.024]same with the same seed: Trueaudit: ['S06' 'S11' 'S09']stores = np.array([f"S{i:02d}" for i in range(1, 13)])# TODO: rng = ..., five normal readings, a second generator, compare, 3 distinct storesHint 1
np.random.default_rng(42) creates a seeded generator. rng.normal(loc, scale, size) draws normal values.
Hint 2
rng.choice(stores, size=3, replace=False) draws 3 different stores.
Solution
stores = np.array([f"S{i:02d}" for i in range(1, 13)])rng = np.random.default_rng(42)readings = rng.normal(loc=22.0, scale=0.5, size=5)again = np.random.default_rng(42).normal(loc=22.0, scale=0.5, size=5)audit = rng.choice(stores, size=3, replace=False)print(readings)print("same with the same seed:", np.array_equal(readings, again))print("audit:", audit)assert np.array_equal(readings, again)assert len(set(audit.tolist())) == 3[22.152 21.48 22.375 22.47 21.024]same with the same seed: Trueaudit: ['S06' 'S11' 'S09']How it works:
- Two generators with the same seed produce the same sequence of numbers, so the 5 readings are identical.
replace=Falsemakes every pick distinct. Thesetin the assert checks it.- The audit uses the first generator after its 5 draws, so it continues the same reproducible sequence.
M23-C01 · Humidity per sensor
Section titled “M23-C01 · Humidity per sensor”data/sensors.csv is sorted by timestamp and then by sensor (S1 to S4). Load the humidity column, reshape it to a timestamp × sensor matrix, and print, for each sensor, the mean, minimum and maximum humidity (ignoring gaps) and the number of missing values. End with the name of the driest sensor.
S1: mean 55.0%, range 48.3-62.7%, missing 11S2: mean 55.0%, range 45.3-63.6%, missing 8S3: mean 51.3%, range 42.8-60.5%, missing 5S4: mean 55.2%, range 47.9-63.3%, missing 5driest: S3humidity = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=3)names = np.array(["S1", "S2", "S3", "S4"])# TODO: reshape to (timestamps, 4)# TODO: nanmean, nanmin, nanmax and missing count per sensor# TODO: one line per sensor, then the driest sensorHint 1
humidity.reshape(-1, 4) makes 4 columns; NumPy computes the number of rows.
Hint 2
Per sensor means per column: axis=0. argmin() on the 4 means gives the position of the driest sensor.
Solution
humidity = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=3)names = np.array(["S1", "S2", "S3", "S4"])hum = humidity.reshape(-1, 4)means = np.nanmean(hum, axis=0)lows = np.nanmin(hum, axis=0)highs = np.nanmax(hum, axis=0)missing = np.isnan(hum).sum(axis=0)for name, m, lo, hi, n in zip(names, means, lows, highs, missing): print(f"{name}: mean {m:.1f}%, range {lo:.1f}-{hi:.1f}%, missing {n}")print("driest:", names[means.argmin()])assert hum.shape == (2016, 4)assert missing.sum() == 29assert names[means.argmin()] == "S3"S1: mean 55.0%, range 48.3-62.7%, missing 11S2: mean 55.0%, range 45.3-63.6%, missing 8S3: mean 51.3%, range 42.8-60.5%, missing 5S4: mean 55.2%, range 47.9-63.3%, missing 5driest: S3How it works:
- The reshape puts each sensor in its own column, because the file repeats S1, S2, S3, S4 for every timestamp.
- Each NaN-aware reduction over
axis=0returns 4 values, one per sensor. zippairs the five arrays for printing; the computation itself has no loop.- S3 is the driest sensor on average. Its humidity falls from about 55% to 48% over the two weeks, the mirror image of its upward temperature drift: humidity moves against the measured temperature.
Alternative: without the reshape, use one mask per sensor: np.nanmean(humidity[ids == "S1"]) with ids loaded from column 1. This also works when the file is not sorted, at the cost of one pass per sensor.
M23-C02 · Refactor: a nested loop into broadcasting
Section titled “M23-C02 · Refactor: a nested loop into broadcasting”Refactor: the code below computes the share of each quarter in its store’s yearly revenue with three loops. Rewrite it with one broadcasting expression. Also compute, without a loop, each store’s difference from the quarter average. Check that your shares equal the loop result.
[[0.16 0.231 0.225 0.384] [0.202 0.199 0.24 0.359] [0.208 0.135 0.247 0.41 ]][[ 4013.667 16785.333 9595.333 19583.333] [ 2619.667 -14.667 699.333 -3887.667] [ -6633.333 -16770.667 -10294.667 -15695.667]]same as the loop: Truesouth = np.array([ [33792, 48602, 47361, 80978], [32398, 31802, 38465, 57507], [23145, 15046, 27471, 45699],])shares_loop = np.zeros(south.shape)for i in range(south.shape[0]): total = 0 for j in range(south.shape[1]): total += south[i, j] for j in range(south.shape[1]): shares_loop[i, j] = south[i, j] / total# TODO: shares = one expression with broadcasting# TODO: difference from the quarter average, one expressionHint 1
The inner loop computes one total per row. Which reduction gives one total per row, with a shape that can divide a (3, 4) matrix?
Hint 2
south.sum(axis=1, keepdims=True) has shape (3, 1). The quarter average is south.mean(axis=0), with shape (4,).
Solution
south = np.array([ [33792, 48602, 47361, 80978], [32398, 31802, 38465, 57507], [23145, 15046, 27471, 45699],])shares_loop = np.zeros(south.shape)for i in range(south.shape[0]): total = 0 for j in range(south.shape[1]): total += south[i, j] for j in range(south.shape[1]): shares_loop[i, j] = south[i, j] / total
shares = south / south.sum(axis=1, keepdims=True)vs_average = south - south.mean(axis=0)print(shares)print(vs_average)print("same as the loop:", np.allclose(shares, shares_loop))assert np.allclose(shares, shares_loop)assert np.allclose(shares.sum(axis=1), 1)assert np.allclose(vs_average.sum(axis=0), 0)[[0.16 0.231 0.225 0.384] [0.202 0.199 0.24 0.359] [0.208 0.135 0.247 0.41 ]][[ 4013.667 16785.333 9595.333 19583.333] [ 2619.667 -14.667 699.333 -3887.667] [ -6633.333 -16770.667 -10294.667 -15695.667]]same as the loop: TrueHow it works:
south.sum(axis=1, keepdims=True)is a(3, 1)column of store totals. Broadcasting stretches it across the 4 quarters, so each element is divided by its own row’s total.south.mean(axis=0)is a(4,)row of quarter averages. Broadcasting subtracts it from every row.- The deviations of each quarter add up to 0, a quick check that the right average was subtracted.
Alternative: south / south.sum(axis=1)[:, np.newaxis] adds the length-1 axis by indexing instead of keepdims.
M23-C03 · Fix the bug: standardize the right axis
Section titled “M23-C03 · Fix the bug: standardize the right axis”Fix the bug: the code below should standardize three house features (sqft, bedrooms, bathrooms, columns 2 to 4 of data/houses.csv), so that each column has mean 0 and standard deviation 1. It raises an error. Fix it, then print the column means and standard deviations before and after, and the z-scores of the first house.
before: [1856.637 3.017 2.624] [711.831 1.275 0.908]after: True [1. 1. 1.]first house: [2420. 4. 3.5] -> [0.791 0.772 0.965]features = np.genfromtxt("data/houses.csv", delimiter=",", skip_header=1, usecols=(2, 3, 4))z = (features - features.mean(axis=1)) / features.std(axis=1) # BUGprint(z[0])Hint 1
Read the error message: which two shapes does NumPy try to broadcast? Print features.shape and features.mean(axis=1).shape.
Hint 2
A feature is a column. One mean per column means that the row axis disappears.
Solution
features = np.genfromtxt( "data/houses.csv", delimiter=",", skip_header=1, usecols=(2, 3, 4))mu = features.mean(axis=0)sigma = features.std(axis=0)z = (features - mu) / sigmaprint("before:", mu, sigma)print("after: ", np.allclose(z.mean(axis=0), 0), z.std(axis=0))print("first house:", features[0], "->", z[0])assert features.shape == (3000, 3) and mu.shape == (3,)assert np.allclose(z.mean(axis=0), 0) and np.allclose(z.std(axis=0), 1)before: [1856.637 3.017 2.624] [711.831 1.275 0.908]after: True [1. 1. 1.]first house: [2420. 4. 3.5] -> [0.791 0.772 0.965]How it works:
- The buggy
mean(axis=1)computes one mean per house: shape(3000,). Aligned from the right with(3000, 3), the axes 3 and 3000 differ, so broadcasting fails withValueError: operands could not be broadcast together with shapes (3000,3) (3000,). axis=0gives one mean and one standard deviation per column: shape(3,), which broadcasts over all 3,000 rows.- The first house has 2,420 sqft, 4 bedrooms and 3.5 bathrooms: all above average, so all three z-scores are positive.
np.allclose(..., 0)is used for the means because floating-point rounding leaves values such as1e-16.
Alternative: in a project, use scikit-learn’s StandardScaler (module 34). It computes the same thing and remembers mu and sigma to apply them to new data.
M23-C04 · Rank the stores
Section titled “M23-C04 · Rank the stores”The matrix below holds the real 2024 revenue of all 12 stores by quarter (USD, rounded). Print the top 3 stores by yearly revenue with their totals, and the top 3 by Q4 revenue. Use np.argsort and fancy indexing, not a loop or sorted().
top year: ['S07' 'S01' 'S10'] [263923 220900 213238]top Q4: ['S07' 'S01' 'S04'] [106229 82368 80978]stores = np.array([f"S{i:02d}" for i in range(1, 13)])q2024 = np.array([ [40722, 45357, 52453, 82368], [21926, 27811, 33103, 58803], [16664, 34934, 24725, 38865], [33792, 48602, 47361, 80978], [32398, 31802, 38465, 57507], [23145, 15046, 27471, 45699], [44927, 50249, 62518, 106229], [31147, 32071, 29535, 55600], [23803, 28980, 32567, 47138], [45606, 40648, 49269, 77715], [30924, 29005, 28423, 52824], [26430, 14983, 16545, 33802],])# TODO: yearly totals, positions of the top 3, names and totals# TODO: the same for the Q4 columnHint 1
np.argsort(x) returns positions from the smallest to the largest value. Reverse them with [::-1] and keep the first 3.
Hint 2
Index stores and the totals with the same positions, so that names and values stay aligned.
Solution
stores = np.array([f"S{i:02d}" for i in range(1, 13)])q2024 = np.array([ [40722, 45357, 52453, 82368], [21926, 27811, 33103, 58803], [16664, 34934, 24725, 38865], [33792, 48602, 47361, 80978], [32398, 31802, 38465, 57507], [23145, 15046, 27471, 45699], [44927, 50249, 62518, 106229], [31147, 32071, 29535, 55600], [23803, 28980, 32567, 47138], [45606, 40648, 49269, 77715], [30924, 29005, 28423, 52824], [26430, 14983, 16545, 33802],])yearly = q2024.sum(axis=1)top_year = np.argsort(yearly)[::-1][:3]top_q4 = np.argsort(q2024[:, 3])[::-1][:3]print("top year:", stores[top_year], yearly[top_year])print("top Q4: ", stores[top_q4], q2024[top_q4, 3])assert stores[top_year].tolist() == ["S07", "S01", "S10"]assert yearly[top_year[0]] == yearly.max()assert stores[top_q4].tolist() == ["S07", "S01", "S04"]top year: ['S07' 'S01' 'S10'] [263923 220900 213238]top Q4: ['S07' 'S01' 'S04'] [106229 82368 80978]How it works:
yearlyhas one total per store.np.argsort(yearly)lists the positions from the smallest to the largest total.[::-1]reverses the order and[:3]keeps the 3 largest.stores[top_year]andyearly[top_year]use the same positions, so each name stays with its total.q2024[top_q4, 3]combines fancy indexing on the rows with a single column index.- S04 (Houston) is fourth over the year but third in Q4, ahead of S10.
Alternative: for very large arrays, np.argpartition(yearly, -3)[-3:] finds the top 3 without a full sort, but in no particular order; sort those 3 afterwards.
M23-C05 · Price bands with np.select
Section titled “M23-C05 · Price bands with np.select”Label every house of data/houses.csv (columns sqft and price, positions 2 and 13) as "budget" (price below 300,000), "mid" (below 600,000) or "premium". Print the number of houses per band and the median size per band, in the order budget, mid, premium.
budget 939 houses, median 1,320 sqftmid 1413 houses, median 1,740 sqftpremium 648 houses, median 2,530 sqfthouses = np.genfromtxt("data/houses.csv", delimiter=",", skip_header=1, usecols=(2, 13))sqft, price = houses[:, 0], houses[:, 1]# TODO: band = np.select(...)# TODO: counts per band, median sqft per bandHint 1
np.select takes a list of conditions and a list of choices. The first True condition wins, so the second condition can simply be price < 600_000.
Hint 2
For each band label, sqft[band == label] keeps the sizes of that band. A loop over the 3 labels is fine: the work inside it is vectorized.
Solution
houses = np.genfromtxt( "data/houses.csv", delimiter=",", skip_header=1, usecols=(2, 13))sqft, price = houses[:, 0], houses[:, 1]band = np.select( [price < 300_000, price < 600_000], ["budget", "mid"], default="premium")counts = {}for label in ["budget", "mid", "premium"]: in_band = band == label counts[label] = int(in_band.sum()) median_sqft = np.median(sqft[in_band]) print(f"{label:<8} {in_band.sum():>5} houses, median {median_sqft:,.0f} sqft")assert sum(counts.values()) == len(price)assert counts == {"budget": 939, "mid": 1413, "premium": 648}budget 939 houses, median 1,320 sqftmid 1413 houses, median 1,740 sqftpremium 648 houses, median 2,530 sqftHow it works:
np.selectchecksprice < 300_000first. Only houses that fail it reach the second condition, so"mid"means 300,000 to 599,999.default="premium"covers every house that fails both conditions.band == labelis a mask;sqft[mask]keeps the matching sizes fornp.median.- Bigger houses fall into more expensive bands, but the size ranges overlap: the neighborhood matters too.
Alternative: np.digitize(price, [300_000, 600_000]) returns the band number 0, 1 or 2 for each house, and np.bincount of those numbers gives the counts in one call.
M23-C06 · Cap extreme prices
Section titled “M23-C06 · Cap extreme prices”The house prices in data/houses.csv are right-skewed and contain a few injected outliers. Cap them at the 1st and 99th percentile with np.clip (this is called winsorizing). Print the two percentiles, how many prices were changed at each end, and the mean before and after.
1st percentile: 166,995, 99th percentile: 1,765,690raised: 30 lowered: 30mean before: 476,466, after: 473,196price = np.genfromtxt("data/houses.csv", delimiter=",", skip_header=1, usecols=13)# TODO: p1, p99 = np.percentile(...)# TODO: capped = np.clip(...)# TODO: counts at each end, mean before and afterHint 1
np.percentile(price, [1, 99]) returns both percentiles in one array; unpack it into two names.
Hint 2
A price changed at the low end when price < p1. Count the masks with .sum().
Solution
price = np.genfromtxt("data/houses.csv", delimiter=",", skip_header=1, usecols=13)p1, p99 = np.percentile(price, [1, 99])capped = np.clip(price, p1, p99)print(f"1st percentile: {p1:,.0f}, 99th percentile: {p99:,.0f}")print("raised:", (price < p1).sum(), "lowered:", (price > p99).sum())print(f"mean before: {price.mean():,.0f}, after: {capped.mean():,.0f}")assert capped.min() == p1 and capped.max() == p99assert (capped != price).sum() == (price < p1).sum() + (price > p99).sum()assert capped.mean() < price.mean()1st percentile: 166,995, 99th percentile: 1,765,690raised: 30 lowered: 30mean before: 476,466, after: 473,196How it works:
np.percentilesorts internally and interpolates between neighbors, so a percentile need not be a price that occurs in the data.np.clipreplaces every value belowp1withp1and every value abovep99withp99. It returns a new array.- 30 houses change at each end (1% of 3,000). The mean falls by about 3,300 USD because the top tail is longer than the bottom tail.
Alternative: in a cleaning pipeline, use a mask to flag the extreme rows instead ((price < p1) | (price > p99)) and inspect them before you decide. Module 26 compares capping, removal and robust methods.
M23-C07 · Interpret: the SVD of the store matrix
Section titled “M23-C07 · Interpret: the SVD of the store matrix”Interpret a result: compute the SVD of the 12 × 4 matrix q2024 of M23-C04. Print the share of the sum of squares held by each singular value and the first store pattern (with the sign flipped to positive), scaled so that its largest value is 1. Then answer in two sentences: what does the first share say about the stores, and which store does the scaled pattern mark as the smallest?
shares: [0.992 0.004 0.003 0.001]store pattern: [0.82 0.54 0.42 0.79 0.59 0.42 1. 0.55 0.49 0.79 0.52 0.34]smallest: S12 largest: S07stores = np.array([f"S{i:02d}" for i in range(1, 13)])q2024 = np.array([ [40722, 45357, 52453, 82368], [21926, 27811, 33103, 58803], [16664, 34934, 24725, 38865], [33792, 48602, 47361, 80978], [32398, 31802, 38465, 57507], [23145, 15046, 27471, 45699], [44927, 50249, 62518, 106229], [31147, 32071, 29535, 55600], [23803, 28980, 32567, 47138], [45606, 40648, 49269, 77715], [30924, 29005, 28423, 52824], [26430, 14983, 16545, 33802],])# TODO: U, s, Vt = np.linalg.svd(...)# TODO: shares of s**2, first store pattern scaled to max 1, smallest storeHint 1
Use full_matrices=False. The share of singular value k is s[k]**2 / np.sum(s**2).
Hint 2
The first store pattern is the column U[:, 0]. Its sign is arbitrary: if its values are negative, multiply by −1. Divide by its maximum to scale.
Solution
stores = np.array([f"S{i:02d}" for i in range(1, 13)])q2024 = np.array([ [40722, 45357, 52453, 82368], [21926, 27811, 33103, 58803], [16664, 34934, 24725, 38865], [33792, 48602, 47361, 80978], [32398, 31802, 38465, 57507], [23145, 15046, 27471, 45699], [44927, 50249, 62518, 106229], [31147, 32071, 29535, 55600], [23803, 28980, 32567, 47138], [45606, 40648, 49269, 77715], [30924, 29005, 28423, 52824], [26430, 14983, 16545, 33802],])U, s, Vt = np.linalg.svd(q2024, full_matrices=False)shares = s**2 / np.sum(s**2)pattern = U[:, 0] * np.sign(U[:, 0].sum()) # make it positivescaled = pattern / pattern.max()print("shares:", shares)print("store pattern:", scaled.round(2))print("smallest:", stores[scaled.argmin()], "largest:", stores[scaled.argmax()])assert np.isclose(shares.sum(), 1)assert shares[0] > 0.95assert stores[scaled.argmin()] == "S12"shares: [0.992 0.004 0.003 0.001]store pattern: [0.82 0.54 0.42 0.79 0.59 0.42 1. 0.55 0.49 0.79 0.52 0.34]smallest: S12 largest: S07Interpretation: the first singular value holds 99.2% of the sum of squares, so the 12 stores follow almost the same quarterly shape and differ mainly by size. The store pattern ranks S12 (Denver, the newest and smallest store) lowest at about a third of S07 (New York).
How it works:
svdsplits the matrix into store patterns (U), strengths (s) and quarter patterns (Vt).- Squared singular values add up to the total sum of squares, so dividing by their sum gives shares that add up to 1.
np.sign(U[:, 0].sum())is −1 when the pattern came out negative. Multiplying fixes the sign without changing the meaning.
Alternative: check the rank-1 claim directly: np.linalg.norm(q2024 - s[0] * np.outer(U[:, 0], Vt[0])) / np.linalg.norm(q2024) gives the relative error of the one-pattern approximation: about 0.09, the square root of the 0.8% that the first pattern misses.
M23-C08 · Predict the output: shapes
Section titled “M23-C08 · Predict the output: shapes”Predict the output: write down the shape (or value) that each line prints. Then run the code.
a = np.arange(24)grid = a.reshape(4, 6)print(grid.shape, a.reshape(2, -1, 3).shape)print(np.concatenate([grid, grid]).shape, np.concatenate([grid, grid], axis=1).shape)print(np.stack([a, a]).shape, np.stack([a, a], axis=1).shape)print(grid.sum(axis=0).shape, grid.sum(axis=1, keepdims=True).shape)print(grid[:, np.newaxis, :].shape, grid.T.shape)print(len(np.split(a, 4)), np.split(a, 4)[1])print((grid[:, :1] + grid[:1, :]).shape)Acceptance criteria: write your prediction line by line, then run the code. Your prediction matches the Output in the solution.
Hint 1
concatenate keeps the number of axes and grows one of them. stack adds a new axis.
Hint 2
grid[:, :1] has shape (4, 1) and grid[:1, :] has shape (1, 6). Apply the broadcasting rule.
Solution
a = np.arange(24)grid = a.reshape(4, 6)print(grid.shape, a.reshape(2, -1, 3).shape)print(np.concatenate([grid, grid]).shape, np.concatenate([grid, grid], axis=1).shape)print(np.stack([a, a]).shape, np.stack([a, a], axis=1).shape)print(grid.sum(axis=0).shape, grid.sum(axis=1, keepdims=True).shape)print(grid[:, np.newaxis, :].shape, grid.T.shape)print(len(np.split(a, 4)), np.split(a, 4)[1])print((grid[:, :1] + grid[:1, :]).shape)assert a.reshape(2, -1, 3).shape == (2, 4, 3)assert np.stack([a, a], axis=1).shape == (24, 2)assert (grid[:, :1] + grid[:1, :]).shape == (4, 6)(4, 6) (2, 4, 3)(8, 6) (4, 12)(2, 24) (24, 2)(6,) (4, 1)(4, 1, 6) (6, 4)4 [ 6 7 8 9 10 11](4, 6)How it works:
reshape(2, -1, 3): 24 elements / (2 × 3) = 4 for the-1axis.concatenatejoins along axis 0 by default, which stacks the rows (8 × 6); on axis 1 it joins the columns (4 × 12).stackadds a new axis at the given position:(2, 24)or(24, 2).sum(axis=0)removes axis 0;keepdims=Truekeeps axis 1 with length 1.np.newaxisinserts an axis of length 1;.Tswaps the two axes.np.split(a, 4)gives 4 parts of 6; the second is 6 to 11.(4, 1) + (1, 6)broadcasts to(4, 6): an outer sum.
M23-C09 · Recover prices from order totals
Section titled “M23-C09 · Recover prices from order totals”Three Home-category orders are known only by their units and their list-price totals. The products are the Espresso Machine (P006), the Robot Vacuum (P007) and the Chef’s Knife Set (P008). Order 1: 2, 1 and 3 units, total 1,387.84 USD. Order 2: 1, 2 and 0 units, total 948.98 USD. Order 3: 0, 1 and 4 units, total 819.79 USD. Set up the linear system and solve it for the three unit prices. Check the result with units @ prices.
prices: [349. 299.99 129.95]check: [1387.84 948.98 819.79]determinant: 15.0units = np.array([ # TODO: one row per order, one column per product])totals = np.array([1387.84, 948.98, 819.79])# TODO: prices = np.linalg.solve(...)# TODO: print the prices and check units @ prices against totalsHint 1
Each order is one equation: 2 * p6 + 1 * p7 + 3 * p8 = 1387.84. The matrix holds the coefficients, one row per equation.
Hint 2
np.linalg.solve(A, b) finds x with A @ x == b. Round the result to cents for printing.
Solution
units = np.array([ [2, 1, 3], # order 1: P006, P007, P008 [1, 2, 0], # order 2 [0, 1, 4], # order 3])totals = np.array([1387.84, 948.98, 819.79])prices = np.linalg.solve(units, totals)print("prices:", prices.round(2))print("check:", units @ prices)print(f"determinant: {np.linalg.det(units):.1f}")assert np.allclose(units @ prices, totals)assert np.allclose(prices, [349.0, 299.99, 129.95])prices: [349. 299.99 129.95]check: [1387.84 948.98 819.79]determinant: 15.0How it works:
- The unknowns are the three prices. Each order gives one linear equation, so three orders give a 3 × 3 system.
solvereturns 349.00, 299.99 and 129.95 USD: the list prices indata/products.csv.units @ pricesrebuilds the totals, which proves the solution.- The determinant is one number computed from a square matrix. It is 0 exactly when the matrix has no inverse. Here it is 15, so the system has exactly one solution. If order 3 were the sum of orders 1 and 2, it would add no new information, the determinant would be 0 and
solvewould raiseLinAlgError: Singular matrix.
Alternative: with more orders than products, the system has more equations than unknowns. Use np.linalg.lstsq(units, totals)[0], which finds the best fit and tolerates rounding in the totals.
M23-C10 · Add a feature, drop the gaps
Section titled “M23-C10 · Add a feature, drop the gaps”Extend the least-squares model of the lesson. Load sqft, school_rating and price (columns 2, 11 and 13) of data/houses.csv. school_rating has 90 blanks: keep only complete rows. Fit price = a + b × sqft + c × school_rating with np.linalg.lstsq and print the coefficients and the . Compare with the of sqft alone on the same rows.
complete rows: 2910a = -433,375, b = 275.24 per sqft, c = 61,689 per school pointsqft-only slope on the same rows: 327.45 per sqftR^2 sqft only: 0.531, sqft + school: 0.660data = np.genfromtxt("data/houses.csv", delimiter=",", skip_header=1, usecols=(2, 11, 13))# TODO: complete = rows with no NaN# TODO: design matrices with a column of ones# TODO: lstsq, R^2 for both modelsHint 1
np.isnan(data).any(axis=1) is True for each row with at least one gap. Invert it to keep the complete rows.
Hint 2
Write a small function r_squared(X, y) that fits with lstsq, predicts with X @ coef and returns 1 - SS_res / SS_tot, so both models use the same code.
Solution
data = np.genfromtxt( "data/houses.csv", delimiter=",", skip_header=1, usecols=(2, 11, 13))complete = ~np.isnan(data).any(axis=1)sqft, school, price = data[complete].Tones = np.ones_like(sqft)
def fit(X: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, float]: coef = np.linalg.lstsq(X, y)[0] residuals = y - X @ coef r2 = 1 - np.sum(residuals**2) / np.sum((y - y.mean()) ** 2) return coef, float(r2)
coef2, r2_two = fit(np.column_stack([ones, sqft, school]), price)coef1, r2_one = fit(np.column_stack([ones, sqft]), price)print("complete rows:", complete.sum())a, b, c = coef2print(f"a = {a:,.0f}, b = {b:.2f} per sqft, c = {c:,.0f} per school point")print(f"sqft-only slope on the same rows: {coef1[1]:.2f} per sqft")print(f"R^2 sqft only: {r2_one:.3f}, sqft + school: {r2_two:.3f}")assert complete.sum() == 3000 - 90assert r2_two > r2_onecomplete rows: 2910a = -433,375, b = 275.24 per sqft, c = 61,689 per school pointsqft-only slope on the same rows: 327.45 per sqftR^2 sqft only: 0.531, sqft + school: 0.660How it works:
.any(axis=1)reduces each row’s 3 NaN flags to one: shape(3000,). 2,910 rows are complete.data[complete].Ttransposes the(2910, 3)block to(3, 2910), so unpacking gives the three columns.- Each extra school-rating point adds about 61,700 USD for a house of the same size. On the same 2,910 rows, the slope for size drops from 327.45 (sqft only) to 275.24 USD per sqft, because part of what size explained is now explained by the school.
- rises from 0.53 to 0.66: the school rating carries information that size does not.
Alternative: instead of dropping rows, fill the gaps with the median rating (np.where(np.isnan(school), np.nanmedian(school), school)). Module 26 compares the two choices; module 34 does it inside a pipeline.
M23-C11 · Choose and justify: eig or eigh
Section titled “M23-C11 · Choose and justify: eig or eigh”Choose a method and justify it: you need the eigenvalues of the correlation matrix of the three numeric columns of data/sensors.csv (temperature, humidity, vibration), using only complete rows. Compute them with both np.linalg.eig and np.linalg.eigh. Print the correlation matrix, the dtype and order of each result, and the share of each eigenvalue. Then say which function you would use and why.
[[ 1. -0.545 0.292] [-0.545 1. 0.139] [ 0.292 0.139 1. ]]symmetric: Trueeig: complex128 [0.317 1.569 1.114]eigh: float64 [0.317 1.114 1.569]shares: [0.106 0.371 0.523]data = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=(2, 3, 4))# TODO: keep complete rows, np.corrcoef(..., rowvar=False)# TODO: eig and eigh, dtypes, values, sharesHint 1
A correlation matrix is symmetric: np.allclose(corr, corr.T) is True.
Hint 2
Compare result.eigenvalues.dtype for both functions. eigh returns its eigenvalues in ascending order.
Solution
data = np.genfromtxt( "data/sensors.csv", delimiter=",", skip_header=1, usecols=(2, 3, 4))complete = data[~np.isnan(data).any(axis=1)]corr = np.corrcoef(complete, rowvar=False)general = np.linalg.eig(corr)symmetric = np.linalg.eigh(corr)print(corr)print("symmetric:", np.allclose(corr, corr.T))print("eig: ", general.eigenvalues.dtype, general.eigenvalues.real)print("eigh:", symmetric.eigenvalues.dtype, symmetric.eigenvalues)print("shares:", symmetric.eigenvalues / symmetric.eigenvalues.sum())assert np.allclose(np.sort(general.eigenvalues.real), symmetric.eigenvalues)assert symmetric.eigenvalues.dtype == np.float64assert np.isclose(symmetric.eigenvalues.sum(), 3)[[ 1. -0.545 0.292] [-0.545 1. 0.139] [ 0.292 0.139 1. ]]symmetric: Trueeig: complex128 [0.317 1.569 1.114]eigh: float64 [0.317 1.114 1.569]shares: [0.106 0.371 0.523]Choice: use eigh. The correlation matrix is symmetric, and eigh is made for that case: it returns real float64 values in ascending order and is faster. eig gives the same numbers as complex values in no guaranteed order, which you would have to clean up with .real and np.sort.
How it works:
- Temperature and humidity have a correlation of −0.55: humidity moves against temperature.
- The eigenvalues of a 3 × 3 correlation matrix add up to 3, so each share is a fraction of the total variation.
- The largest eigenvalue holds only 52%. Unlike the house size columns of the lesson, these three measurements carry different information, so none of them is redundant.
M23-C12 · Simulate a week of orders
Section titled “M23-C12 · Simulate a week of orders”data/sales.csv has a mean of 20.4 orders per day. Model the daily number of orders as a Poisson count (the standard distribution for counts of independent events per interval) with mean 20.4. Simulate 10,000 weeks of 7 days with a generator seeded 42. Print the mean and standard deviation of the weekly totals and the estimated probability that a week has more than 160 orders.
(10000, 7) int64mean 142.7, std 11.9P(week > 160 orders) = 0.068rng = np.random.default_rng(42)# TODO: daily = rng.poisson(..., size=(10_000, 7))# TODO: weekly totals, mean, std, share above 160Hint 1
size=(10_000, 7) draws a whole matrix: one row per simulated week, one column per day.
Hint 2
Sum over the days (axis=1). The probability is the mean of the mask weekly > 160.
Solution
rng = np.random.default_rng(42)daily = rng.poisson(lam=20.4, size=(10_000, 7))weekly = daily.sum(axis=1)print(daily.shape, daily.dtype)print(f"mean {weekly.mean():.1f}, std {weekly.std():.1f}")print(f"P(week > 160 orders) = {(weekly > 160).mean():.3f}")assert weekly.shape == (10_000,)assert abs(weekly.mean() - 7 * 20.4) < 1assert 0.03 < (weekly > 160).mean() < 0.12(10000, 7) int64mean 142.7, std 11.9P(week > 160 orders) = 0.068How it works:
- One call draws all 70,000 days. The result has an integer dtype, because Poisson values are counts.
- The sum of 7 independent Poisson counts with mean 20.4 is Poisson with mean 142.8 and standard deviation √142.8 ≈ 11.9; the simulation agrees.
- The share of simulated weeks above 160 estimates the probability. This Monte Carlo approach (estimating a quantity by simulating many random cases and counting) works for any rule you can simulate, even when no formula exists.
Alternative: the real data has a weekly cycle (Saturday is the peak), which a constant mean ignores. Draw each day with its own mean: rng.poisson(lam=day_means, size=(10_000, 7)), where day_means is a (7,) array that broadcasts across the weeks.
M23-C13 · Fix the bug: the gaps are still there
Section titled “M23-C13 · Fix the bug: the gaps are still there”Fix the bug: this cleaning step should replace the missing temperatures of data/sensors.csv with the mean of the valid ones. After it runs, the gaps are still there and the fill value is nan. Find both bugs and fix them.
fill value: 24.055missing before: 22 after: 0temperature = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=2)fill_value = temperature.mean()filled = temperature.copy()filled[filled == np.nan] = fill_valueprint("fill value:", fill_value)print("missing after:", np.isnan(filled).sum())Hint 1
Print (temperature == np.nan).sum(). How many gaps does this mask find?
Hint 2
NaN is never equal to anything. And the plain mean() of an array with NaN is NaN.
Solution
temperature = np.genfromtxt( "data/sensors.csv", delimiter=",", skip_header=1, usecols=2)fill_value = np.nanmean(temperature)filled = temperature.copy()gaps = np.isnan(filled)filled[gaps] = fill_valueprint(f"fill value: {fill_value:.3f}")print("missing before:", gaps.sum(), "after:", np.isnan(filled).sum())assert gaps.sum() == 22assert not np.isnan(filled).any()assert np.isclose(filled.mean(), fill_value)fill value: 24.055missing before: 22 after: 0How it works:
- Bug 1:
temperature.mean()isnanbecause of the gaps.np.nanmeanskips them. - Bug 2:
filled == np.nanisFalseeverywhere, because NaN is not equal to itself.np.isnanfinds the gaps. - The masked assignment writes the fill value into the 22 gaps of the copy.
- Filling with the mean keeps the overall mean unchanged, which the last assert checks.
Alternative: np.where(np.isnan(temperature), np.nanmean(temperature), temperature) does the same in one expression and never touches the original. For sensor data, a per-sensor median is a better fill value than the global mean, because the sensors run at different temperatures.
Challenge
Section titled “Challenge”M23-X01 · Spikes against the daily profile
Section titled “M23-X01 · Spikes against the daily profile”Example 2 of the lesson compares each temperature with its sensor’s overall median. A better baseline also respects the daily cycle: compare each reading with the median of the same sensor at the same time of day over the 14 days. Reshape the temperatures of data/sensors.csv to (days, slots, sensors), compute this baseline, flag readings more than 5 °C above it, and print: the number of spikes in total and per sensor, the number of spike days per sensor, and the hour of the day with the most spikes.
baseline shape: (1, 144, 4)spikes: 40 per sensor: [ 8 13 11 8]spike days per sensor: [ 6 11 8 6]peak hour: 16 with 7 spikestemperature = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=2)# TODO: by_day = reshape to (14, 144, 4)# TODO: baseline = median over the days, keepdims# TODO: spike mask, totals per sensor, spike days per sensor, peak hourHint 1
The median over the days is a reduction over axis 0. With keepdims=True it has shape (1, 144, 4), which broadcasts against (14, 144, 4).
Hint 2
A slot is 10 minutes, so slot k belongs to hour k // 6. spike.sum(axis=(0, 2)) counts spikes per slot over all days and sensors; reshape those 144 counts to (24, 6) and sum each row.
Hint 3
A sensor has a spike day when spike[d, :, s].any(). With axes: spike.any(axis=1) has shape (14, 4); sum it over the days.
Solution
temperature = np.genfromtxt( "data/sensors.csv", delimiter=",", skip_header=1, usecols=2)by_day = temperature.reshape(14, 144, 4) # day, ten-minute slot, sensorbaseline = np.nanmedian(by_day, axis=0, keepdims=True)spike = (by_day - baseline) > 5.0per_sensor = spike.sum(axis=(0, 1))spike_days = spike.any(axis=1).sum(axis=0)per_hour = spike.sum(axis=(0, 2)).reshape(24, 6).sum(axis=1)print("baseline shape:", baseline.shape)print("spikes:", spike.sum(), "per sensor:", per_sensor)print("spike days per sensor:", spike_days)print("peak hour:", per_hour.argmax(), "with", per_hour.max(), "spikes")assert spike.sum() == 40assert np.array_equal(per_sensor, [8, 13, 11, 8])assert per_hour.sum() == 40 and (spike_days <= 14).all()baseline shape: (1, 144, 4)spikes: 40 per sensor: [ 8 13 11 8]spike days per sensor: [ 6 11 8 6]peak hour: 16 with 7 spikesHow it works:
- The file order (timestamp, then sensor) matches row-order reshaping, so
(14, 144, 4)puts each day, slot and sensor on its own axis. - The median over axis 0 is the typical temperature of each sensor at each time of day.
keepdims=Truekeeps shape(1, 144, 4)so that broadcasting lines up the slots and sensors. - A tuple of axes reduces several axes at once:
axis=(0, 1)leaves one count per sensor. spike.any(axis=1)asks “any spike in this day for this sensor?”, and the sum over days counts those days.- Reshaping 144 slot counts to
(24, 6)groups 6 slots per hour.
Alternative: this baseline also finds exactly the 40 spikes, like the overall median, because the spikes are much larger than the daily cycle. For subtler anomalies (for example +3 °C at 03:00, when the room is coolest), the time-of-day baseline catches what the overall median misses.
M23-X02 · Revenue by store, category and region
Section titled “M23-X02 · Revenue by store, category and region”Build a stores × categories revenue matrix from data/sales.csv with np.unique and np.bincount. Print each store’s Electronics share and name the store that depends most on Electronics. Then aggregate the stores into regions with a matrix product: build a regions × stores 0/1 matrix from data/stores.csv and multiply. Print the revenue per region and check it against the data dictionary (East 993,684, South 891,766, North 888,229, West 822,845, rounded).
['Beauty' 'Books' 'Clothing' 'Electronics' 'Home' 'Sports']Electronics share: [0.513 0.484 0.452 0.52 0.511 0.438 0.533 0.521 0.527 0.506 0.443 0.532]most dependent: S07East: 993,684South: 891,766North: 888,229West: 822,845import csv
with open("data/sales.csv", newline="", encoding="utf-8") as f: sales_rows = list(csv.DictReader(f))with open("data/stores.csv", newline="", encoding="utf-8") as f: store_rows = list(csv.DictReader(f))# TODO: arrays of store_id, category, revenue# TODO: positions with np.unique(..., return_inverse=True)# TODO: matrix with np.bincount on a combined position# TODO: Electronics share per store, top store# TODO: regions x stores 0/1 matrix, region revenue with @Hint 1
A cell (i, j) of an n_stores × n_categories matrix has the flat position i * n_categories + j. np.bincount(flat, weights=revenue, minlength=...) adds the revenue of each flat position; reshape the result.
Hint 2
The 0/1 matrix has one row per region and one column per store: region_of_store == regions[:, np.newaxis] builds it by broadcasting. Make sure the store order matches the matrix rows.
Hint 3
membership @ store_total gives one sum per region, because each row of membership selects the stores of one region.
Solution
import csv
with open("data/sales.csv", newline="", encoding="utf-8") as f: sales_rows = list(csv.DictReader(f))with open("data/stores.csv", newline="", encoding="utf-8") as f: store_rows = list(csv.DictReader(f))
store_col = np.array([r["store_id"] for r in sales_rows])cat_col = np.array([r["category"] for r in sales_rows])revenue = np.array([float(r["revenue"]) for r in sales_rows])store_names, store_pos = np.unique(store_col, return_inverse=True)categories, cat_pos = np.unique(cat_col, return_inverse=True)n_s, n_c = len(store_names), len(categories)flat = store_pos * n_c + cat_posmatrix = np.bincount(flat, weights=revenue, minlength=n_s * n_c).reshape(n_s, n_c)
store_total = matrix.sum(axis=1)elec_share = matrix[:, categories == "Electronics"].ravel() / store_totalprint(categories)print("Electronics share:", elec_share.round(3))print("most dependent:", store_names[elec_share.argmax()])
region_of_store = np.array([r["region"] for r in store_rows])assert [r["store_id"] for r in store_rows] == store_names.tolist()regions = np.array(["East", "South", "North", "West"])membership = (region_of_store == regions[:, np.newaxis]).astype(float) # (4, 12)by_region = membership @ store_totalfor name, value in zip(regions, by_region): print(f"{name}: {value:,.0f}")assert membership.shape == (4, 12) and (membership.sum(axis=0) == 1).all()assert np.allclose(by_region.round(), [993684, 891766, 888229, 822845])assert np.isclose(matrix.sum(), revenue.sum())['Beauty' 'Books' 'Clothing' 'Electronics' 'Home' 'Sports']Electronics share: [0.513 0.484 0.452 0.52 0.511 0.438 0.533 0.521 0.527 0.506 0.443 0.532]most dependent: S07East: 993,684South: 891,766North: 888,229West: 822,845How it works:
np.unique(..., return_inverse=True)maps each label to its position in the sorted list of labels.- The flat position
store * n_categories + categoryturns a pair of positions into one integer.np.bincountwithweightssums the revenue per integer, andreshapefolds the result into the matrix. categories == "Electronics"is a mask over the 6 columns; selecting with it keeps a(12, 1)block, whichravel()flattens.region_of_store == regions[:, np.newaxis]compares a(12,)row with a(4, 1)column: a(4, 12)table that is 1 where a store belongs to a region.- Multiplying that table by the store totals sums the stores of each region. This is a group-by written as a matrix product, the same operation that a one-hot encoding (module 33) feeds into a linear model.
Alternative: np.add.at(matrix, (store_pos, cat_pos), revenue) fills the matrix directly from the two position arrays, as in lesson Example 3. bincount is usually faster for large data.
M23-X03 · Refactor: from functions to a SensorLog class
Section titled “M23-X03 · Refactor: from functions to a SensorLog class”Refactor procedural code into a class: the script below loads data/sensors.csv and computes per-sensor means, spikes and cleaned means with loose variables. Turn it into a frozen dataclass SensorLog that holds a (timestamps, 4) temperature matrix and the sensor names. Give it a from_csv(path) class method, a mean_by_sensor() method, a spikes(threshold) method that returns a boolean mask, and a without(mask) method that returns a new SensorLog with the masked readings set to NaN. The original must never change.
(2016, 4) spikes: 40raw: {'S1': 22.051, 'S2': 24.602, 'S3': 23.529, 'S4': 26.038}clean: {'S1': 21.999, 'S2': 24.519, 'S3': 23.46, 'S4': 25.986}temperature = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=2)temp = temperature.reshape(-1, 4)means = np.nanmean(temp, axis=0)median = np.nanmedian(temp, axis=0)spike = (temp - median) > 5.0clean = temp.copy()clean[spike] = np.nanclean_means = np.nanmean(clean, axis=0)print(means, spike.sum(), clean_means)# TODO: rewrite as a SensorLog dataclass with from_csv, mean_by_sensor, spikes, withoutHint 1
Use @dataclass(frozen=True, eq=False) with two fields, temps: np.ndarray and names: tuple[str, ...]. A @classmethod named from_csv loads and reshapes the file and returns cls(...).
Hint 2
frozen=True stops you from reassigning log.temps, but it does not stop log.temps[0, 0] = 0. In without, copy the matrix before you write NaN into it.
Solution
from dataclasses import dataclassfrom typing import Self
@dataclass(frozen=True, eq=False) # eq=False: == on arrays is element-wiseclass SensorLog: """Temperatures as a (timestamps, sensors) matrix."""
temps: np.ndarray names: tuple[str, ...] = ("S1", "S2", "S3", "S4")
@classmethod def from_csv(cls, path: str) -> Self: column = np.genfromtxt(path, delimiter=",", skip_header=1, usecols=2) return cls(column.reshape(-1, 4))
def mean_by_sensor(self) -> dict[str, float]: means = np.nanmean(self.temps, axis=0) return {n: round(float(m), 3) for n, m in zip(self.names, means)}
def spikes(self, threshold: float = 5.0) -> np.ndarray: median = np.nanmedian(self.temps, axis=0) return (self.temps - median) > threshold
def without(self, mask: np.ndarray) -> Self: cleaned = self.temps.copy() cleaned[mask] = np.nan return type(self)(cleaned, self.names)
log = SensorLog.from_csv("data/sensors.csv")spike = log.spikes()clean = log.without(spike)print(log.temps.shape, "spikes:", spike.sum())print("raw: ", log.mean_by_sensor())print("clean:", clean.mean_by_sensor())assert spike.sum() == 40assert np.isnan(clean.temps).sum() == np.isnan(log.temps).sum() + 40assert not np.shares_memory(clean.temps, log.temps)(2016, 4) spikes: 40raw: {'S1': 22.051, 'S2': 24.602, 'S3': 23.529, 'S4': 26.038}clean: {'S1': 21.999, 'S2': 24.519, 'S3': 23.46, 'S4': 25.986}How it works:
- The dataclass bundles the matrix with its column names, so they cannot drift apart.
eq=Falsekeeps identity comparison: the generated__eq__would compare the arrays with==, which returns an array, andbool()of that array raisesValueError. from_csvis an alternative constructor (module 18).Self(module 12) types it so that subclasses return their own type.- Each method is one vectorized expression; the class adds names and structure, not loops.
withoutcopies before writing. The last assert proves that the cleaned log has its own memory, so the raw data is safe.float(m)androundturn NumPy scalars into plain floats, so the dicts print withoutnp.float64(...).
Alternative: make spikes and without one method, remove_spikes(threshold). Separate methods are better here: you can inspect the mask (count it, list its timestamps) before you remove anything.
M23-X04 · Gradient descent against the closed form
Section titled “M23-X04 · Gradient descent against the closed form”Fit the house-price line of the lesson by gradient descent instead of lstsq. Use standardized size (z-scores of sqft) and price in thousands of USD as , so the numbers stay small. The model is and the loss is the mean squared error. Its gradients are
Start at , use a learning rate of 0.1 and run 100 steps, all vectorized. Print the loss at steps 0, 10, 50 and 99, the final and , the lstsq solution on the same data, and the slope converted back to USD per sqft.
step 0: loss 328,587.4step 10: loss 50,683.4step 50: loss 47,442.0step 99: loss 47,442.0gradient descent: w = 232.650, b = 476.465lstsq: w = 232.650, b = 476.466slope: 326.83 USD per sqfthouses = np.genfromtxt("data/houses.csv", delimiter=",", skip_header=1, usecols=(2, 13))sqft, price = houses[:, 0], houses[:, 1]# TODO: x = z-scores of sqft, y = price / 1000# TODO: w, b = 0.0, 0.0; loop 100 steps: predict, error, gradients, update# TODO: compare with lstsq on [ones, x]; convert w to USD per sqftHint 1
Inside the loop: error = w * x + b - y, then grad_w = 2 * np.mean(error * x) and grad_b = 2 * np.mean(error). Update with w -= lr * grad_w.
Hint 2
is in standard deviations of sqft and in thousands of USD. One sqft is standard deviations, so the slope in USD per sqft is w * 1000 / sqft.std().
Solution
houses = np.genfromtxt( "data/houses.csv", delimiter=",", skip_header=1, usecols=(2, 13))sqft, price = houses[:, 0], houses[:, 1]x = (sqft - sqft.mean()) / sqft.std()y = price / 1000w, b, lr = 0.0, 0.0, 0.1for step in range(100): error = w * x + b - y if step in (0, 10, 50, 99): print(f"step {step:>2}: loss {np.mean(error**2):,.1f}") w -= lr * 2 * np.mean(error * x) b -= lr * 2 * np.mean(error)exact = np.linalg.lstsq(np.column_stack([np.ones_like(x), x]), y)[0]print(f"gradient descent: w = {w:.3f}, b = {b:.3f}")print(f"lstsq: w = {exact[1]:.3f}, b = {exact[0]:.3f}")print(f"slope: {w * 1000 / sqft.std():.2f} USD per sqft")assert np.allclose([b, w], exact, atol=1e-3)assert np.isclose(w * 1000 / sqft.std(), 326.83, atol=0.01)step 0: loss 328,587.4step 10: loss 50,683.4step 50: loss 47,442.0step 99: loss 47,442.0gradient descent: w = 232.650, b = 476.465lstsq: w = 232.650, b = 476.466slope: 326.83 USD per sqftHow it works:
- Standardizing makes the loss surface round, so one learning rate suits both parameters and descent converges in a few dozen steps.
- Each step is four vectorized lines over 3,000 houses: no inner loop over rows.
- The loss falls quickly and then flattens at the minimum, which
lstsqcomputes in one step. - With standardized, is the mean price (476.5 thousand USD) and the change per standard deviation of size. Dividing by the standard deviation of sqft (712 sqft) gives back the lesson’s 326.83 USD per sqft.
Alternative: run the same loop on raw sqft. With a learning rate of 0.1, the loss grows about a trillion times per step and overflows to inf (with a RuntimeWarning) after about 25 steps, because the gradient for is thousands of times larger than for and every step overshoots. This is why ML pipelines scale features before gradient-based training (modules 32 and 42).
M23-X05 · How many patterns does the sales matrix need?
Section titled “M23-X05 · How many patterns does the sales matrix need?”Rebuild the 12 × 24 stores × months revenue matrix of lesson Example 3 from data/sales.csv. Compute its SVD. Print the cumulative share of the sum of squares for the first 5 singular values, the smallest number of components that reaches 99%, and the relative reconstruction error for . Then interpret: is the rank-1 approximation good enough to forecast one store’s next December?
cumulative: [0.954 0.965 0.973 0.979 0.984]components for 99%: 7k=1: relative error 0.215k=2: relative error 0.186k=3: relative error 0.165import csv
with open("data/sales.csv", newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f))# TODO: positions of stores and months, matrix with np.add.at# TODO: svd, cumulative shares, smallest k for 99%# TODO: rank-k approximation and relative error for k = 1, 2, 3Hint 1
np.cumsum(s**2) / np.sum(s**2) gives the cumulative shares. np.argmax(shares >= 0.99) finds the first position where the condition is True; add 1 to turn a position into a count.
Hint 2
The rank-k approximation is U[:, :k] @ np.diag(s[:k]) @ Vt[:k], or with broadcasting (U[:, :k] * s[:k]) @ Vt[:k]. np.linalg.norm of a matrix is the square root of its sum of squares.
Solution
import csv
with open("data/sales.csv", newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f))_, store_pos = np.unique([r["store_id"] for r in rows], return_inverse=True)_, month_pos = np.unique([r["order_date"][:7] for r in rows], return_inverse=True)M = np.zeros((12, 24))np.add.at(M, (store_pos, month_pos), [float(r["revenue"]) for r in rows])
U, s, Vt = np.linalg.svd(M, full_matrices=False)cumulative = np.cumsum(s**2) / np.sum(s**2)k99 = int(np.argmax(cumulative >= 0.99)) + 1print("cumulative:", cumulative[:5].round(4))print("components for 99%:", k99)for k in (1, 2, 3): approx = (U[:, :k] * s[:k]) @ Vt[:k] rel = np.linalg.norm(M - approx) / np.linalg.norm(M) print(f"k={k}: relative error {rel:.3f}")assert np.isclose(M.sum(), 3_596_523.83)assert cumulative[k99 - 1] >= 0.99 > cumulative[k99 - 2]cumulative: [0.954 0.965 0.973 0.979 0.984]components for 99%: 7k=1: relative error 0.215k=2: relative error 0.186k=3: relative error 0.165Interpretation: one pattern holds 95.4% of the sum of squares, but its relative error is still about 21%. Each value of a single store-month is noisy (a few large Electronics orders move it a lot), so it takes 7 patterns to reach 99%, and most of those later patterns describe noise. The rank-1 pattern is a good summary of store size and seasonality, and a reasonable baseline for a forecast. It is not accurate enough for one store’s December on its own: module 40 adds trend and proper forecasting models.
How it works:
np.uniqueaccepts plain lists and returns the positions directly;_discards the labels.cumsumof the squared singular values, divided by their total, gives the share of the first components for every at once.argmaxon a boolean array returns the firstTrueposition.U[:, :k] * s[:k]scales each of the first columns by its singular value (broadcasting a(k,)row), which avoids buildingnp.diag.- The relative error is the square root of the share that the approximation misses: .
M23-X06 · Interpret: a permutation test for online orders
Section titled “M23-X06 · Interpret: a permutation test for online orders”Interpret a result: is the mean revenue of an online sales line really different from that of a store line in data/sales.csv, or could the difference be chance? Run a permutation test: shuffle the channel labels 2,000 times with a generator seeded 42, recompute the difference of the means each time, and report the share of shuffles whose absolute difference is at least as large as the observed one (the p-value). Print the observed difference, the middle 95% of the shuffled differences and the p-value, then state your conclusion in one sentence.
online lines: 8495, store lines: 11733observed gap: 1.84 USD95% of shuffled gaps: -8.50 to 8.82 USDp-value: 0.678import csv
with open("data/sales.csv", newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f))revenue = np.array([float(r["revenue"]) for r in rows])online = np.array([r["channel"] == "online" for r in rows])# TODO: observed difference of the means (online - store)# TODO: 2,000 shuffles of the mask with rng.permutation# TODO: middle 95% of the shuffled differences, p-valueHint 1
If the channel made no difference, any assignment of the 8,495 “online” labels to the lines would be as likely as the real one. rng.permutation(online) creates one such assignment.
Hint 2
Store the differences in np.empty(2000). The p-value is np.mean(np.abs(diffs) >= abs(observed)).
Solution
import csv
with open("data/sales.csv", newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f))revenue = np.array([float(r["revenue"]) for r in rows])online = np.array([r["channel"] == "online" for r in rows])
def mean_gap(mask: np.ndarray) -> float: return float(revenue[mask].mean() - revenue[~mask].mean())
observed = mean_gap(online)rng = np.random.default_rng(42)diffs = np.empty(2000)for k in range(2000): diffs[k] = mean_gap(rng.permutation(online))low, high = np.percentile(diffs, [2.5, 97.5])p_value = np.mean(np.abs(diffs) >= abs(observed))print(f"online lines: {online.sum()}, store lines: {(~online).sum()}")print(f"observed gap: {observed:.2f} USD")print(f"95% of shuffled gaps: {low:.2f} to {high:.2f} USD")print(f"p-value: {p_value:.3f}")assert online.sum() == 8495assert low < observed < highassert 0 <= p_value <= 1online lines: 8495, store lines: 11733observed gap: 1.84 USD95% of shuffled gaps: -8.50 to 8.82 USDp-value: 0.678Conclusion: the observed gap of 1.84 USD lies well inside the range of gaps that random labels produce, and about 68% of the shuffles give a gap at least as large, so the data give no evidence that an online line earns more than a store line.
How it works:
rng.permutation(online)returns a shuffled copy of the mask: the same number ofTruevalues, at random positions. That is the “no difference” world.- Each shuffle recomputes the gap with two masked means: vectorized over 20,228 lines. 2,000 shuffles take well under a second.
- The middle 95% of the shuffled gaps (about −8.50 to +8.82 USD) shows how big a gap chance alone produces.
- A large p-value does not prove that the means are equal. It says that this data cannot tell them apart. Module 29 covers hypothesis tests, p-values and effect sizes in depth.
Alternative: a two-sample t-test (scipy.stats.ttest_ind, module 29) gives a similar answer in one call. The permutation test needs no assumption about the shape of the distribution, which matters here because line revenue is very skewed.