Skip to content
Learn Python with BNHR

Stretch: processing

On this page
  1. Overview
  2. S1.1 · A variable's table, from its name
  3. S1.2 · Rows that share a key
  4. S1.3 · The households a region's table still holds, as a polars table
  5. S1.4 · Member rows beside the household's count
  6. S1.5 · Drop exact copies, keep everything else

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.

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.

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.

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.

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.

Something new

Identify results
LayerExplore a stretch exercises
Stretch exercises S2Stretch: tabulation
AboutStretch exercises S2 of Python for Survey Statistics, after module 7: more tabulation, for those who finish early or want more.
CoursePython for Survey Statistics, free