Skip to content
Learn Python with BNHR

Start here

On this page
  1. Overview
  2. 1.1 · Codes that are not on the list
  3. 1.2 · Step 1, filter: the large-scale units that are not voided
  4. 1.3 · Step 2, mutate: each boat's gross tonnage
  5. 1.4 · Step 3, inner_join: the catch of the large-scale units

Every exercise in 00_start.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 1.1. Codes that are not on the list

The task

Why it matters: a code outside its list is a keying slip or a code the list forgot. Either way an editor must see it before tabulating, or a table gets a row nobody can label. A blank is a different thing: the education level is blank for members under six, because the question is not asked of them. Reported as an invalid code, every young child would become an edit to make.

Input → output: a column of codes and the list of valid codes → the codes in the column that are not on the list, each once, smallest first, with blanks (missing values) left out. [] when every code is valid.

column valid returns
[1, 2, 9, <NA>, 3, 9] [1, 2] [3, 9]
[1, 2, 2, 1] [1, 2] []

Tools (Arrays & DataFrames, modules 3 and 5): column.dropna() leaves out the blanks; column.isin(valid) is True where a value is on the list, and ~ turns each True to False and back; .unique(); .tolist(); sorted(...).

If the check is red: common causes

what you see the usual cause look at
TypeError: boolean value of NA is ambiguous A blank reached sorted, which cannot compare it with a number. column.dropna() before anything else
[3, 9, None] or a blank in the list The blanks were kept: isin is False for a blank, so ~ keeps it. column.dropna()
[9, 3] Each code once, but in the order they first appear. sorted(...)
[9, 3, 9] One entry per row, not per code. .unique()
[1, 2]: the valid codes The ~ is missing, so the values on the list are kept. ~present.isin(valid)
A column of values shown, not a list The filtered column was returned as it is. .unique().tolist(), then sorted

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 1.2. Step 1, filter: the large-scale units that are not voided

The task

Why it matters: every count of large-scale units starts from this filter. Written the dplyr way without the blank in mind, it keeps no row at all, and every table after it comes out empty with no error.

Input → output: a fishing units table as the database holds it → its rows whose unit_scale is 2 and whose row_void is blank or not 1, every column kept.

region_code hh_id unit_scale row_void kept?
01 5012 2 blank yes
01 5013 2 1 no: voided in editing
04 5204 1 blank no: small-scale
07 5088 2 blank yes

In R: units |> filter(unit_scale == 2, is.na(row_void) | row_void != 1).

Tools: the keep rows and is blank rows of the translation table: table[(condition) & (condition)], .isna(), and | for or, with brackets around each comparison.

If the check is red: common causes

what you see the usual cause look at
0 rows for the survey row_void != 1 alone: it is blank for a blank mark, and a row with a blank condition is dropped. Or row_void == 0: the mark is never 0. Or units["row_void"].isna() | units["row_void"] != 1 with no brackets around the comparison: | is worked out before !=, with no error. units["row_void"].isna() | (units["row_void"] != 1)
The second of the five units is kept The void mark is not tested. the second condition
Small-scale units (unit_scale 1) are kept The scale is not tested, or tested with != 1 on a column that could hold other values. units["unit_scale"] == 2
TypeError: Cannot perform 'rand_' ... or TypeError: 'other' should be pandas.NA or a bool A comparison without its own brackets: & and | are worked out before == and !=. a pair of brackets around each comparison
ValueError: The truth value of a Series is ambiguous and or or between two columns of conditions, or two comparisons chained without brackets. & and |, and brackets
Fewer columns than the input Columns were selected after the filter. return units[...] with every column

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 1.3. Step 2, mutate: each boat's gross tonnage

The task

Why it matters: a unit is large-scale when one of its boats is 5.0 gross tons or more, so the tonnage decides which table every unit is counted in. The questionnaire takes a boat's size from its registration papers, or measures it in meters or in feet (boat_measured_in), and the formula depends on which. The capture program stores a tonnage too (boat_tonnage), but stored figures can be wrong; computing it again is how module 4 checks them.

Input → output: a boats table → the same table with one more column at the end, gt, the boat's gross tonnage, by rule B3 of codebook_rules.csv:

boat_measured_in, where the size comes from gt
1, the registration papers boat_tonnage_reported, the tonnage on the papers
2, measured in meters boat_length × boat_beam × boat_depth × 0.212
3, measured in feet boat_length × boat_beam × boat_depth × 0.006

For example, a boat measured in meters, 10 long, 1 wide and 0.5 deep, is 10 × 1 × 0.5 × 0.212 = 1.06 gross tons. Mind the order of the codes: 1 is the papers, not meters.

In R:

boats |> mutate(gt = case_when(
  boat_measured_in == 1 ~ boat_tonnage_reported,
  boat_measured_in == 2 ~ boat_length * boat_beam * boat_depth * 0.212,
  boat_measured_in == 3 ~ boat_length * boat_beam * boat_depth * 0.006
))

Tools: the a column by cases row of the translation table: np.select([conditions], [values], default=np.nan), the conditions and the values in the same order; table.assign(gt=...) returns the table with the new column.

If the check is red: common causes

what you see the usual cause look at
About 38 for the second small boat, not 1.08 Feet multiplied by 0.212, the factor for meters. * 0.006 for a boat measured in feet
A blank gt for the third small boat Only two cases (an np.where on meters or feet): the papers' tonnage is never taken. a condition boat_measured_in == 1, with boat_tonnage_reported
0.03 for the first small boat, and blanks for the next two The codes read in another order (1 as meters, 2 as feet, 3 as the papers). the codebook's values for boat_measured_in: 1 is the papers
4.8 for the fourth small boat The stored boat_tonnage was copied; it is wrong for that boat. compute boat_length * boat_beam * boat_depth * 0.212
ValueError: list of cases must be same length as list of conditions np.select was given three conditions and two values, or the other way round. the two lists, in the same order
No gt column, or gt not last The result was not added as a column, or the columns were reordered. boats.assign(gt=...)

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 1.4. Step 3, inner_join: the catch of the large-scale units

The task

Why it matters: the catch table does not say whether its unit is large-scale; only the units table does. An inner join keeps the catch rows whose unit is in the large-scale set and drops the rest. It needs the whole key: without region_code a household of region 01 matches the household with the same id in region 07, and without unit_no a member's second unit matches their first.

If the check is red: common causes

what you see the usual cause look at
KeyError: 'operator_line' The catch's key parts still have their catch_ names. catch.rename(columns=CATCH_KEY) first
A row of region 07 in the small table's result region_code is not in the key, so household 5012 of region 07 matched region 01's. all four parts: on=UNIT_KEY
Species 203 in the small table's result unit_no is not in the key, so the member's second unit matched the first. all four parts
Species 101 in the result, or a row with a blank species A left or outer join: unmatched rows were kept. how="inner"
Columns such as row_id_x and row_id_y, or more than five columns The whole units table was joined, or the five columns were not selected. units[UNIT_KEY], then [UNIT_KEY + ["catch_species"]]
MergeError: Merge keys are not unique in right dataset A unit is in the units table twice. The check gives none; your own call may have used every unit, with the copy shown above. the units with the copy dropped, as large is

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 module
ModuleDataFrames
AboutModule 3 of Arrays & DataFrames: Series and the index, reading files with the right types, selecting and sorting, and new columns under pandas 3's copy-on-write. Its sections, its notebooks to read on the web, and the companion's solutions and explanations.
CourseArrays & DataFrames, free