Every exercise in 10_arrays.py, with the solution and why it works. Each answer stays closed until you swear you tried it first. Opening one changes nothing in your notebook; your check still has to go green from your own code. Read the whole notebook, with its lessons.
Exercise 2.1. Class limits for a histogram
The task
Why it matters: the histogram above let matplotlib choose its ranges. A report fixes its own, so charts from different years compare: plots of 0 to 0.5 hectares, 0.5 to 1, and so on. A histogram takes these class limits (its bins=) as an array.
Input → output: the lowest limit, the highest limit and the number of classes → an array of the limits, decimals (float64), lowest first.
low |
high |
n_classes |
limits |
|---|---|---|---|
| 0 | 4 | 8 | [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0] |
| 0 | 1 | 4 | [0.0, 0.25, 0.5, 0.75, 1.0] |
Count them: 8 classes need 9 limits, as 8 sections of fence need 9 posts.
Tools: np.linspace(start, stop, num), from Arrays without data above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| 8 limits instead of 9, with widths such as 0.571 | One limit too few: as many limits as classes. | n_classes + 1 |
| The last limit (4.0) is missing | np.arange stops before its stop. |
np.linspace, which includes both ends |
| holds whole numbers for 2 to 6 | np.arange with whole numbers gives int64. |
np.linspace, which always gives decimals |
| TypeError: 'float' object cannot be interpreted as an integer | The number of limits passed to linspace is a decimal, as after a /. |
num must be a whole number: n_classes + 1 |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Evenly spaced numbers that include both ends are what np.linspace makes; the only thing to get right is how many, which is one more than the number of classes.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def class_edges(low: float, high: float, n_classes: int) -> np.ndarray: """The limits of n_classes equal classes from low to high, both ends included, as decimals.""" # Exercise 2.1: the task and examples are in the text above this cell. return np.linspace(low, high, n_classes + 1)Why each part is there
np.linspace(low, high, n_classes + 1): the classes sit between the limits, so there is always one limit more than classes.np.linspace(low, high, n_classes)gives one class too few, with uneven widths such as 0.571 instead of 0.5.linspaceincludeshigh.np.arange(low, high, width)stops beforehigh, so the last limit goes missing;np.arange(low, high + width, width)can work, but decimal steps can land a hair above or belowhigh, whichlinspacenever does.linspacealways returns decimals (float64), even for whole-number limits such as 2, 4 and 6, so the limits of every histogram are the same type.
Exercise 2.2. One row per year
The task
Why it matters: 48 monthly prices in one long row are hard to compare. Laid out as one row per year, January to December, each column is one calendar month across the years, and section 4 averages a whole year in one step.
Input → output: a 1-D array of monthly values, starting in January, whose length is a whole number of years → the same values, one row per year and 12 columns.
| input | output shape | output |
|---|---|---|
np.arange(1, 25) (24 months) |
(2, 12) |
row 0 is 1 … 12, row 1 is 13 … 24 |
| 48 monthly prices of one province | (4, 12) |
row 0 is 2022, row 3 is 2025 |
Your function must work for any number of whole years, not only four.
Tools: .reshape(...) with -1, from reshape above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| ValueError: cannot reshape array of size 12 into shape (4,12) | The number of years is fixed at 4. | -1 for the rows |
Shape (12, 1) or (12, 3) |
Rows and columns swapped: 12 rows. | reshape(-1, 12): 12 columns |
Shape (3, 12), but the values are out of order |
The array was transposed (.T) after reshaping to 12 rows. |
rows fill first: reshape straight to 12 columns |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Reshape to rows of 12 and let NumPy count the rows: the values stay in order, so January to December of each year fills one row.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def by_year(monthly: np.ndarray) -> np.ndarray: """Monthly values starting in January, laid out as one row per year of 12 months.""" # Exercise 2.2: the task and examples are in the text above this cell. return monthly.reshape(-1, 12)Why each part is there
monthly.reshape(-1, 12): 12 is the number of columns, one per month, and-1asks NumPy for as many rows as it takes, which is the number of years. It works for 1, 2 or 4 years alike.reshape(4, 12)is right for the price grid's 48 months only; a 24-month input raises cannot reshape array of size 24 into shape (4,12).reshape(12, -1)has the right number of values but the wrong layout: 12 rows, with the months of a year spread down a column. Rows fill first, so the 12 must be the number of columns.
Exercise 2.3. Irrigated rice
The task
Why it matters: irrigation is the largest difference between rice plots. Section 3 compares the yields of irrigated and rain-fed rice, and both groups start from this mask.
Input → output: the plots' crop and irrigated arrays → a boolean mask, True for each plot that grows rice and is irrigated.
| crop | irrigated | in the mask |
|---|---|---|
| Rice | Yes | True |
| Rice | No | False |
| Corn | Yes | False |
| (not recorded) | Yes | False |
Tools: ==, & and brackets, from Combining conditions above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| ValueError: The truth value of an array with more than one element is ambiguous | and instead of &. |
& between the two masks |
| TypeError: unsupported operand type(s) for &: 'str' and 'str' | A comparison without brackets: & ran before ==. |
(crop == "Rice") & (irrigated == "Yes") |
Irrigated corn is True |
The "or" operator instead of & (and). |
& |
Every plot is False |
A spelling the data doesn't use, such as "rice" or "yes". |
the exact text: "Rice", "Yes" |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Two comparisons give two masks of the same length; & keeps the plots that are in both. Each comparison needs its own brackets.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def irrigated_rice(crop: np.ndarray, irrigated: np.ndarray) -> np.ndarray: """True for each plot that grows rice and is irrigated.""" # Exercise 2.3: the task and examples are in the text above this cell. return (crop == "Rice") & (irrigated == "Yes")Why each part is there
crop == "Rice"andirrigated == "Yes"each give oneTrueorFalseper plot. A plot with no crop recorded holdsnan, which is not equal to "Rice", so it isFalsewithout any special case.&combines them element by element:Trueonly where both are.|would give rice or irrigated, which includes irrigated corn.- The brackets are required:
&is read before==, so without them Python tries"Rice" & irrigatedand raises a TypeError.andraises the ValueError the truth value of an array … is ambiguous.
Exercise 2.4. One year of prices
The task
Why it matters: reports compare years: 2025 against 2024. In the price grid a year is twelve columns side by side, and taking them is a slice by position.
Input → output: a grid with one row per province and one column per month, starting in January 2022, and a year → the columns of that year, every row: shape (rows, 12).
The year's first column is 12 for each year since 2022:
| year | columns | slice |
|---|---|---|
| 2022 | 0 to 11 | 0:12 |
| 2023 | 12 to 23 | 12:24 |
| 2025 | 36 to 47 | 36:48 |
Tools: a grid slice grid[:, start:stop], from By position above. Work out start and stop from year.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
Shape (2, 36), (0, 36) or (0, 48) |
The slice took rows, not columns. | grid[:, start:stop] |
Shape (2, 11) |
The stop is one short: it is not included. | stop = start + 12 |
| The values are one month late | The start counts from 1, or from 2021. | 2022 starts at column 0 |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A year is a run of 12 columns that starts 12 columns later for each year after 2022; slice every row and those columns.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def prices_in_year(grid: np.ndarray, year: int) -> np.ndarray: """The 12 columns of one year from a grid of months that starts in January 2022: every row, shape (rows, 12).""" # Exercise 2.4: the task and examples are in the text above this cell. start = (year - 2022) * 12 return grid[:, start:start + 12]Why each part is there
start = (year - 2022) * 12: 2022 starts at column 0, each later year 12 columns further.grid[:, start:start + 12]: the:before the comma keeps every row (province), and the slice after it takes the columns. The stop is not included, sostart + 12gives exactly 12 columns.grid[start:start + 12]without:,slices rows instead: provinces, not months.
Exercise 2.5. Every area in hectares
The task
Why it matters: section 1's histogram showed 151 plots recorded in square meters. Left as they are, a plot of 1,940 square meters counts as 1,940 hectares, and its yield comes out 10,000 times too small. Every total, mean and yield of area needs one unit.
Input → output: the plots' area and unit arrays → every area in hectares, as decimals. One hectare is 10,000 square meters.
| area | unit | area in hectares |
|---|---|---|
| 0.5 | ha | 0.5 |
| 2500 | sqm | 0.25 |
| 10000 | sqm | 1.0 |
Tools: a mask (section 2), / (above) and np.where. Return a new array; don't change area itself.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| 2500 is still 2500 | The square meters were not converted. | np.where(unit == "sqm", ...) |
| 2500 became 2.5 | Divided by 1,000. | 10,000 square meters in a hectare |
| 0.5 ha became 0.00005 | The mask picks the hectare plots. | unit == "sqm" |
| 2500 became 0, or 5000 became 0 | // drops the remainder, or a whole-number array was assigned into. |
/ and np.where, which return decimals |
| holds whole numbers | The result kept the input's whole-number dtype. | area / 10_000 gives decimals |
| ValueError: assignment destination is read-only | Assigning into area[...]: the survey's arrays can't be changed (section 2). |
np.where, which builds a new array |
| UFuncTypeError: Cannot cast ufunc 'divide' output from dtype('float64') to dtype('int64') | /= into a whole-number array, which can't hold decimals. |
np.where |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Divide where the unit is square meters and keep the area elsewhere: np.where picks between the two, plot by plot, into a new array.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def area_in_hectares(area: np.ndarray, unit: np.ndarray) -> np.ndarray: """Every area in hectares: areas recorded in square meters divided by 10,000, the others as they are.""" # Exercise 2.5: the task and examples are in the text above this cell. return np.where(unit == "sqm", area / 10_000, area)Why each part is there
unit == "sqm"is the mask of the plots to convert. Testingunit == "ha"and dividing where it isTruewould convert the wrong plots.area / 10_000divides every area, which is cheap;np.wherethen keeps the divided value only where the mask isTrue. A hectare is 10,000 square meters, not 1,000./gives decimals.//would drop the remainder: 2,500 square meters would become 0 hectares.np.wherereturns a new array and leavesareaas it was. Assigning intoarea[mask]instead fails on the survey's array, which is read-only (assignment destination is read-only); on a copy of whole-number areas it turns 0.5 into 0, because a whole-number array can only hold whole numbers.
Exercise 2.6. A price index for every province
The task
Why it matters: provinces start from different prices, so their raw prices are hard to compare. A price index sets each province's first month to 100: an index of 125 means prices rose 25% since then, whatever the starting price.
Input → output: a grid with one row per province and one column per month → the same shape, each value divided by its own row's first value, times 100, as decimals. A missing price stays nan.
| Jan | Feb | Mar | index | Jan | Feb | Mar | ||
|---|---|---|---|---|---|---|---|---|
| province A | 10 | 12 | 15 | → | province A | 100 | 120 | 150 |
| province B | 20 | 20 | 25 | → | province B | 100 | 100 | 125 |
Tools: a slice that keeps the first column as a column, shape (rows, 1): grid[:, :1] (section 2), and broadcasting (above). grid[:, 0] gives a row of shape (rows,); read the table above to see why that fails.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| ValueError: operands could not be broadcast together with shapes (2,3) (2,) | grid[:, 0] is a row, lined up with the months. |
grid[:, :1], a column |
| Right for the first case, wrong for the square one | grid[:, 0] again: with as many rows as columns it broadcasts, along the wrong direction. |
grid[:, :1] |
| Province B's January is 200, not 100 | Divided by the first row, grid[0], not each row's first value. |
grid[:, :1] |
| Values such as 1.2 instead of 120 | The 100 * is missing. |
100 * grid / ... |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Divide the whole grid by a column of each row's first value: broadcasting stretches that column across the months, so each province is divided by its own start.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def price_index(grid: np.ndarray) -> np.ndarray: """Each row's values as an index: 100 times each value divided by its row's first value.""" # Exercise 2.6: the task and examples are in the text above this cell. return 100 * grid / grid[:, :1]Why each part is there
grid[:, :1]slices the first column and keeps it two-dimensional, shape(rows, 1). Lined up with(rows, months)from the right, its 1 is stretched across every month.grid[:, 0]has shape(rows,), which lines up with the months instead. With 7 provinces and 48 months that raises operands could not be broadcast together; with as many rows as columns it silently divides each column by the wrong province.grid[0](the first row) also broadcasts without complaint, but divides every province by the first province's prices.100 *makes it an index rather than a ratio./always gives decimals, andnandivided by anything staysnan, so the missing month stays missing.
Exercise 2.7. Months with a price, for each province
The task
Why it matters: before averaging, say how much there is to average. A province mean over 47 months is not the same claim as one over 48, and a report states how many values each mean rests on.
Input → output: a grid with one row per province and one column per month → for each row, the number of values that are not nan, as whole numbers.
| Jan | Feb | Mar | Apr | months with a price | ||
|---|---|---|---|---|---|---|
| province A | 18.2 | nan |
18.9 | 19.1 | → | 3 |
| province B | nan |
nan |
20.4 | 20.0 | → | 2 |
Tools: np.isnan and ~ (a mask, then turned around), and .sum(axis=...), which counts the True in each row.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
[1, 2] instead of [3, 2] |
Counted the missing values, not the ones there. | ~np.isnan(grid) |
[3, 2, 1] instead of [1, 2, 3], or one count per month |
Summed down the rows. | axis=1 |
[4, 4], or [48, 48, ...] |
Every value counted: count_nonzero, len, or grid != np.nan. |
np.isnan, which finds nan |
| holds decimals | The count was turned into decimals, as with * 1.0. |
a summed mask is already whole numbers |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Counting is summing a mask: mark each value that is there, then add up the marks across each row.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def months_reported(grid: np.ndarray) -> np.ndarray: """For each row of the grid, how many of its values are not nan.""" # Exercise 2.7: the task and examples are in the text above this cell. return (~np.isnan(grid)).sum(axis=1)Why each part is there
np.isnan(grid)marks the missing values;~turns the mask around to mark the values that are there.grid != np.nancannot do it:nanis not equal to anything, itself included, so that mask isTrueeverywhere..sum(axis=1)adds across the columns, one total per row, andTruecounts as 1.axis=0would count per month instead.- Summing a mask gives whole numbers (
int64), which is what a count is.np.count_nonzero(grid, axis=1)looks similar but countsnanas a value, sincenanis not zero.
Exercise 2.8. The monthly average across provinces
The task
Why it matters: a single national line shows the trend that seven lines hide: the monthly average of the provinces. A month where one province didn't report still has an average of the others; the month with no file at all has none, and the chart should show a gap there, not an invented value.
Input → output: a grid with one row per province and one column per month → for each month, the mean of the values that are not nan. A month with no value at all gives nan.
| Jan | Feb | Mar | |||
|---|---|---|---|---|---|
| province A | 10 | nan |
12 | ||
| province B | 14 | 16 | nan |
||
| average | 12 | 16 | 12 | ← | each month's mean of what is there |
Tools: a nan-aware mean along the right axis, from the tables above. NumPy warns Mean of empty slice for a month with no value; that is expected.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
nan for February and March in the first case |
The mean spreads nan. |
np.nanmean |
| Two values instead of three, or 7 instead of 48 | Averaged across the columns: one per province. | axis=0 |
| Right for the first case, wrong for the square one | axis=1 again: with as many rows as columns, the shape is right and the values are not. |
axis=0 |
| One number | No axis: the mean of every value. | axis=0 |
0 for the month with no prices |
np.nansum was used: the sum of no values is 0, not nan. |
np.nanmean, which gives nan |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
One value per month means summarizing down the provinces, axis=0, with the mean that leaves missing values out.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def monthly_average(grid: np.ndarray) -> np.ndarray: """For each column of the grid, the mean of its values that are not nan (nan if it has none).""" # Exercise 2.8: the task and examples are in the text above this cell. return np.nanmean(grid, axis=0)Why each part is there
axis=0summarizes down the rows, so the rows (provinces) disappear and one value per column (month) is left: shape(48,)for the palay grid.axis=1gives one value per province.np.nanmeanaverages only the values that are there: February's mean in the example is 16, from one province.grid.mean(axis=0)givesnanfor every month with any province missing.- A month with no value at all still gives
nan, with the warning Mean of empty slice: there is nothing to average, andnanis the honest answer. Filling it in is a separate decision (module 5).