Every exercise in 36_stretch_processing.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.
Stretch S1.1. A variable's table, from its name
The task
Why it matters: a joined table holds columns from several tables, and a codebook is read one table at a time. A function that turns a variable's name into its table lets you look any column up, and tells the survey's variables from the columns every table carries, such as the capture system's row_id.
Input → output: a variable's name → the name of its table, or None when the name carries no table's short name. The setup cell holds the short names in TABLE_OF_PREFIX, a dictionary from short name to table: "mem" gives "member", "land" gives "landing".
name |
returns | why |
|---|---|---|
"mem_age" |
"member" |
mem is the member table's short name |
"land_name" |
"landing" |
the short name is not always the table's name: look it up |
"catch_operator_line" |
"catch" |
a child table's copy of a key part carries the child's short name |
"hh_id" |
"household" |
the household's id, which every table carries, is named for the household |
"row_id" |
None |
a capture-system column of every table: row is no table's short name |
"catch" |
None |
a table's name with no _: not a variable |
The rule: cut the name at its first _. It names a table when there is a _, something follows it, and the part before it is a short name in TABLE_OF_PREFIX.
Tools (Python Essentials, modules 2 and 6): name.partition("_") gives the part before the first _, the _ itself (empty text when there is none) and the rest; dict.get(key), which gives None for a key the dictionary does not have; and, which stops at the first test that is False.
If the check is red
Cut at the first "" with partition; if there is a "" and something after it, look the part before it up in TABLE_OF_PREFIX.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Cut the name at its first _, and look the part before it up among the tables' short names; a name with no _, or nothing after it, names no variable.
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 variable_table(name: str) -> str | None: """The table a variable's name says it belongs to ("mem_age" is "member"), or None for a name that names no table.""" # Exercise S1.1: the task and examples are in the text above this cell. prefix, underscore, rest = name.partition("_") if underscore and rest: return TABLE_OF_PREFIX.get(prefix) return NoneWhy each part is there
partition("_")cuts at the first_only, socatch_operator_linegivescatchand the rest whole.split("_")[0]would cut the same, but gives the whole name back when there is no_, andcatch, a table's name, would then look like a variable of the catch table.- Testing the
_and the rest is what tells a variable from a bare short name:"catch"and"boat_"both come backNone. TABLE_OF_PREFIX.get(prefix)looks the short name up:landis the landing table andaidthe assistance table, so the short name alone is not the table's name..getgivesNoneforroworregion, the capture system's and the area codes' columns, which every table or several carry.
Stretch S1.2. Rows that share a key
The task
Why it matters: before you join on a key, check that it names one row. A key that repeats multiplies the rows of every join that uses it. The survey's rule U1 says the unit key is unique, and this function tests it. It counts every row of a repeated key, the first one included, because an editor needs all of them side by side to decide which to keep.
Input → output: a table and a list of its column names (the key) → how many rows share their key with at least one other row. 0 when the key is unique.
| region_code | hh_id |
|---|---|
| 01 | 5101 |
| 07 | 5101 |
| 07 | 5103 |
| 07 | 5103 |
| 07 | 5103 |
rows_sharing_key(table, ["hh_id"]) gives 5: 5101 twice and 5103 three times. rows_sharing_key(table, ["region_code", "hh_id"]) gives 3: the three rows of region 07's household 5103.
Tools (Arrays & DataFrames, module 5): table.duplicated(subset=key, keep=False) is True on every row whose key appears more than once; without keep=False it marks only the repeats after the first. .sum() counts the True values, and int(...) makes the count a plain number.
If the check is red
Mark every row of a repeated key with duplicated(subset=key, keep=False), then count the marks.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
duplicated with keep=False marks every row of a repeated key, not only the repeats; counting the marks gives the rows an editor has to look at.
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 rows_sharing_key(table: pd.DataFrame, key: list[str]) -> int: """How many rows of the table share their key (a list of column names) with at least one other row.""" # Exercise S1.2: the task and examples are in the text above this cell. return int(table.duplicated(subset=key, keep=False).sum())Why each part is there
subset=keycompares only the key's columns. Without it,duplicatedcompares whole rows, and two rows with the same key but any other difference count as unique.keep=Falsemarks the first row of a repeated key too. The default,keep="first", leaves it unmarked: for the example it gives 3 instead of 5, the extra copies rather than the rows involved..sum()adds upTrueas 1 andFalseas 0, so it counts the marked rows.int(...)turns NumPy's integer into Python's, which prints and compares as a plain number; the check would accept either.
Stretch S1.3. The households a region's table still holds, as a polars table
The task
Why it matters: this filter is the first line of every query on the survey. Written with <>, it keeps no household at all; written right, it leaves out the removed households and nothing else.
Input → output: a connection to one regional database → a polars DataFrame of the rows of household still in the survey by the household table's own two marks, every column, ordered by hh_id. A household is kept when hh_deleted_on is blank (it was never deleted in the capture system) and row_void is not 1 (blank or any other value):
| hh_id | … | hh_deleted_on | row_void | kept? |
|---|---|---|---|---|
| 5201 | … | (blank) | (blank) | yes |
| 5202 | … | (blank) | 1 | no: voided in editing |
| 5204 | … | 2026-05-30 | (blank) | no: deleted in the capture system |
| 5205 | … | (blank) | 0 | yes |
The third mark, sel_excluded, is in the selection table; module 2's Exercise 2.3 leaves those households out with a subquery.
Tools: a SELECT ... WHERE ... ORDER BY query, IS NULL, IS DISTINCT FROM, and con.sql(query).pl(), all from module 2, section 1.
If the check is red
Keep hh_deleted_on IS NULL and row_void IS DISTINCT FROM 1, order by hh_id, and return .pl().
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Keep the households with no deletion date and a void flag that is not 1, saying what a blank flag means, and hand the rows to polars.
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 live_households(con: duckdb.DuckDBPyConnection) -> pl.DataFrame: """The household rows not deleted (hh_deleted_on blank) and not voided (row_void not 1), every column, ordered by hh_id, in polars.""" # Exercise S1.3: the task and examples are in the text above this cell. return con.sql("SELECT * FROM household WHERE hh_deleted_on IS NULL AND row_void IS DISTINCT FROM 1 ORDER BY hh_id").pl()Why each part is there
row_void IS DISTINCT FROM 1is true whenrow_voidis blank or any value but 1.row_void <> 1isNULLfor a blank flag, andWHEREdrops those rows: the query would keep only the household whose flag is 0.hh_deleted_on IS NULLkeeps the households with no deletion date.hh_deleted_on = NULLisNULLfor every row, and keeps none.ORDER BY hh_idfixes the order; without it, a database returns rows in whatever order it finds them, and that order is not promised to stay the same..pl()gives a polars table, whoserow_voidstays a whole-number column withnullfor blank, whatever rows are kept.
Stretch S1.4. Member rows beside the household's count
The task
Why it matters: the count of members on the questionnaire's cover and the member roster are written in two places. When they disagree, every estimate per member and per household disagrees with the other.
Input → output: the household table and the member table → the household table, its rows unchanged, with a new column member_rows: the number of the household's rows in the member table, 0 for a household with none.
| region_code | hh_id | hh_roster_members | member_rows |
|---|---|---|---|
| 01 | 5300 | 3 | 3 |
| 04 | 5300 | 2 | 2 |
| 01 | 5301 | 1 | 0 |
Two households share the hh_id 5300, one in each region; each has its own rows.
Tools: groupby(HOUSEHOLD).size(), merge(..., on=HOUSEHOLD, how="left", validate="one_to_one"), fillna(0).
If the check is red
Count members by region and hh_id, left-join the counts onto the households, and fill the missing ones with 0.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Count the member rows per household, then bring the count into the household table with a left join, so every household keeps its row and gets its own count.
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 member_rows(households: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: """The household table with member_rows: the household's rows in the member table (0 if none).""" # Exercise S1.4: the task and examples are in the text above this cell. counts = members.groupby(HOUSEHOLD).size().rename("member_rows").reset_index() out = households.merge(counts, on=HOUSEHOLD, how="left", validate="one_to_one") out["member_rows"] = out["member_rows"].fillna(0).astype("int64") return outWhy each part is there
groupby(HOUSEHOLD), region and household: grouping byhh_idalone adds region 04's household 5300 to region 01's.how="left"keeps every household. A household with no member rows is the strongest failure of H1, and an inner join would drop it before the rule could see it.validate="one_to_one": one count per household and one household row per household. If either repeats, pandas stops rather than copy a household.fillna(0): no member rows is a count of 0, not an unknown count.
Stretch S1.5. Drop exact copies, keep everything else
The task
Why it matters: this is the one edit a program makes on duplicates. It must drop the second of two rows that are the same answer, and nothing else: not a row that shares a key but differs, not the same row in another region.
Input → output: a table and the name of its row id column → the table without the rows that are equal to an earlier row in every column but the row id; the first copy is kept, in the table's order:
| row_id | region_code | hh_id | catch_line | catch_species | |
|---|---|---|---|---|---|
| 1 | 01 | 5300 | 1 | 103 | kept |
| 2 | 01 | 5300 | 1 | 103 | dropped: row 1 again |
| 3 | 04 | 5300 | 1 | 103 | kept: another region |
| 4 | 01 | 5301 | 1 | 304 | kept |
| 5 | 01 | 5301 | 2 | 305 | kept: same unit, another species |
Tools: a list of the columns but one ([c for c in table.columns if c != id_column]), drop_duplicates(subset=..., keep="first").
If the check is red
Compare every column except the row id, and keep the first of rows equal on all of them.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
An exact copy is a row equal to another in everything the respondent and the system could differ in, which is every column but the row id the system gave each stored 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 drop_exact_copies(table: pd.DataFrame, id_column: str) -> pd.DataFrame: """The table without rows equal to an earlier row in every column but the row id; the first copy is kept.""" # Exercise S1.5: the task and examples are in the text above this cell. compared = [column for column in table.columns if column != id_column] return table.drop_duplicates(subset=compared, keep="first")Why each part is there
- Leaving out
id_columnis what makes the copies visible: every stored row has its own id, sodrop_duplicates()on all columns drops nothing. - Comparing every other column, not a key, is what makes the edit safe: two rows that share a key and differ in a value are two answers, and a person chooses between them (U1 or C4 still fails, and the household is referred).
- The region is one of the columns compared, so a household of region 04 is never taken for a copy of region 01's household with the same
hh_id. keep="first"keeps the row stored first, the lower row id in this survey, so the row other tables may already point to stays.