Skip to content
Learn Python with BNHR

Arrays with NumPy

On this page
  1. Overview
  2. 2.1 · Class limits for a histogram
  3. 2.2 · One row per year
  4. 2.3 · Irrigated rice
  5. 2.4 · One year of prices
  6. 2.5 · Every area in hectares
  7. 2.6 · A price index for every province
  8. 2.7 · Months with a price, for each province
  9. 2.8 · The monthly average across provinces

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.

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.

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.

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.

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.

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.

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.

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.

Something new

Identify results
LayerExplore a stretch exercises
Stretch exercises S3Stretch: charts
AboutStretch exercises of Arrays & DataFrames, after module 7: chart exercises on the survey and the prices, in the library of your choice, each with its check and its solution on the companion.
CourseArrays & DataFrames, free