Every exercise in 20_key_matching.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 3.1. The orphans of any child table, by its prefix
The task
Why it matters: this is the first step for every child table at once. One function, given a table's prefix, lists the rows the unit table does not know, so no table is skipped because its column names differ.
Input → output: a child table as the database stores it (children["boat"]), the units, and the table's prefix ("boat") → the child table's rows whose key matches no unit, every column kept, the two key parts under the unit's names. For a small assistance table (prefix aid):
| region_code | row_id | hh_id | operator_line | unit_no | aid_line | aid_kind |
|---|---|---|---|---|---|---|
| 04 | 1 | 5101 | 1 | 1 | 1 | 3 |
| 01 | 3 | 5103 | 1 | 9 | 1 | 4 |
| 01 | 4 | 5107 | 1 | 1 | 1 | 2 |
The first row is the region trap: region 01's household 5101 has a unit with the key 1, 1, and region 04's household 5101 does not. The second names a unit number its operator does not have. The last is a household with no unit at all.
Tools: a dict comprehension inside rename(columns=...), and merge(..., how="left_anti"), above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| KeyError: 'operator_line' on the crew, the catch table passes | The key parts still carry their prefix: the renaming was built for catch_ whatever the table. |
f"{prefix}_{part}" |
Columns such as kind, line or species in the result |
The prefix was stripped from every column that has it, not only from the two key parts. | rename only the two parts |
| The small table's region 04 row is missing | The key left out region_code, so region 04's row found region 01's unit. |
on=KEY |
| Every row of the table comes back | A left or outer join, which keeps the matched rows too. | how="left_anti" |
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
The child tables differ only in their prefix: rename the two parts it marks, and one anti-join on the whole key finds the orphans of any table.
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 orphan_rows(child: pd.DataFrame, units: pd.DataFrame, prefix: str) -> pd.DataFrame: """The rows of a child table whose key matches no unit: every column kept, the key parts renamed to the unit's names.""" # Exercise 3.1: the task and examples are in the text above this cell. renamed = child.rename(columns={f"{prefix}_{part}": part for part in PARTS}) return renamed.merge(units[KEY], on=KEY, how="left_anti")Why each part is there
- The names are built from the prefix and the two parts, so
land(landing sites) andaid(assistance) each rename exactly their own two columns, and no other column is touched. - After the rename, the child and the units share one key list,
KEY, the region included: a row of region 04 never finds a unit of region 01 that shares its household id. how="left_anti"keeps the child rows with no match and adds no column of the units. An anti-join never repeats a row, so a unit entered twice does no harm here.
Exercise 3.2. Operators against the roster
The task
Why it matters: a roster that disagrees with the units is an orphan of another kind. The unit looks run by nobody, or the member's line by someone who runs another number of units. The first step lists it beside the child tables.
Input → output: the members (members) and the units → one row per mismatch, from either side, with the household, the unit side's operator_line and units (how many distinct units name the line; blank for a roster line no unit names), the roster's mem_line, mem_role_operator and mem_units_run (blank where there is no line), and status:
"no roster line": no line of the household has the unit'soperator_line;"operator not flagged": the line is there, and itsmem_role_operatoris not 1 (0 or blank);"count differs": the line is flagged, and itsmem_units_runis not the number of units that name it (a blank count differs too);"flag names no unit": a roster line flagged as an operator that no unit of its household names.
| region_code | hh_id | operator_line | units | mem_line | mem_role_operator | mem_units_run | status |
|---|---|---|---|---|---|---|---|
| 01 | 5202 | 1 | 1 | 1 | 1 | 2 | count differs |
| 01 | 5203 | 3 | 1 | no roster line | |||
| 01 | 5204 | 2 | 1 | 2 | 0 | operator not flagged | |
| 01 | 5204 | 1 | 1 | 1 | flag names no unit | ||
| 01 | 5205 | 2 | 1 | 1 | flag names no unit | ||
| 07 | 5206 | 1 | 1 | 1 | 1 | count differs | |
| 07 | 5207 | 1 | 1 | 1 | flag names no unit |
A unit that names the wrong line shows from both sides, as household 5204 does: the unit finds a line that is not flagged, and the flagged line finds no unit. In household 5205 a second member is flagged; household 5207 has a flagged line and no unit at all. A matched operator has no row, and neither has a member who runs nothing.
Tools: drop_duplicates(), groupby().size(), merge(..., left_on=..., right_on=..., how="left"), fillna, np.select, merge(..., how="left_anti") and pd.concat.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| MergeError: Merge keys are not unique in right dataset; not a many-to-one merge | The join to the roster left out region_code, so regions 01 and 04 share household 5201's lines. |
HOUSEHOLD in left_on and right_on |
The small survey's household 5208 is count differs |
The unit entered twice was counted twice. | step 1, drop_duplicates() before size() |
| A mismatch listed twice with the same status | One row per unit, not per operator: the units were not counted per line. | step 1, groupby(OPERATOR) |
| TypeError: invalid entry 1 in condlist: should be boolean ndarray (the number is the condition's place in the list, from 0) | A comparison with a blank flag or count gave <NA>, which np.select can't take as true or false. |
fillna(0) before != |
| Household 5206 has no row | The blank count was left out of the comparison instead of counted as differing. | mem_units_run.fillna(0) |
| Members who run nothing are listed | The roster side kept every line, not only the flagged lines. | step 4, mem_role_operator == 1 |
No flag names no unit rows |
Only the first direction was run. | step 4 |
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
The unit table and the roster name the operator twice: count each operator's units, join each operator to its line and compare the flag and the count, then look for flagged lines no unit names. The same key check as the catch, run both ways.
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 match_operators(members: pd.DataFrame, units: pd.DataFrame) -> pd.DataFrame: """Every operator whose roster line does not match the units that name it, and every roster line flagged as an operator that no unit names: the household, operator_line, units, mem_line, mem_role_operator, mem_units_run and status.""" # Exercise 3.2: the task and examples are in the text above this cell. operators = units[KEY].drop_duplicates().groupby(OPERATOR).size().rename("units").reset_index() lines = members[HOUSEHOLD + ["mem_line", "mem_role_operator", "mem_units_run"]] side = operators.merge(lines, left_on=OPERATOR, right_on=HOUSEHOLD + ["mem_line"], how="left", validate="many_to_one") side["status"] = np.select( [side["mem_line"].isna(), side["mem_role_operator"].fillna(0) != 1, side["mem_units_run"].fillna(0) != side["units"]], ["no roster line", "operator not flagged", "count differs"], default="matched", ) flagged = lines[lines["mem_role_operator"].fillna(0) == 1] stray = flagged.merge(operators, left_on=HOUSEHOLD + ["mem_line"], right_on=OPERATOR, how="left_anti") stray = stray.assign(status="flag names no unit") return pd.concat([side[side["status"] != "matched"], stray], ignore_index=True)[operator_columns()]Why each part is there
drop_duplicates()before counting: a unit entered twice is one unit, and counting it twice would call a rightmem_units_runwrong.groupby(OPERATOR).size()then gives one row per operator, so a member who runs two units is one row, not two.left_onandright_onpairoperator_linewithmem_lineand keep the household, the region included, in front: region 01's and region 04's household 5201 have different rosters.how="left"keeps the operator whose line is missing.np.selecttests in order, ascase_when()does. A missing line comes first.fillna(0)turns a blank flag or count into 0 before the comparison, where<NA>would be neither True nor False andnp.selectwould refuse it.- The other direction starts from the flagged lines, so a member who runs nothing is never listed. The anti-join on household and line finds a flagged member that no unit names.
pd.concatstacks the two sides; a column one side lacks is blank on its rows.
Exercise 3.3. Catch keys with no unit
The task
Why it matters: this is the first list of the second step. Each line is a catch key the survey's units do not have, with how many catch rows carry it, so the editor sees whether one species or a whole unit's catch is astray.
Input → output: the catch table as stored (key parts catch_operator_line, catch_unit_no) and the units → one row per distinct catch key that matches no unit, with the key under the unit's names and catch_rows, the number of catch rows that carry it:
| region_code | hh_id | operator_line | unit_no | catch_rows |
|---|---|---|---|---|
| 01 | 5101 | 2 | 1 | 1 |
| 01 | 5102 | 2 | 3 | 2 |
| 04 | 5101 | 1 | 1 | 1 |
The last row is the region trap: region 01's household 5101 has a unit with the key 1, 1, and region 04's household 5101 does not. Without region_code in the key, that catch row would find region 01's unit.
Tools: rename(columns={...}), groupby(KEY).size(), and merge(..., how="left_anti"), all above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| KeyError: 'operator_line' | The catch table's parts still start with catch_. |
step 1, rename |
A key repeated, or no catch_rows column |
Catch rows kept, not counted per key. | step 2, groupby(KEY).size() |
| The small survey's region 04 row is missing | The key left out region_code, so region 04's catch found region 01's unit. |
KEY includes region_code |
| Every catch key comes back | An anti-join on the wrong columns, or an outer join without a filter. | how="left_anti", on=KEY |
| ValueError: You are trying to merge on str and int64 columns for key 'region_code' | region_code is text on one side and a number on the other. |
where the tables were read |
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
An orphan is a key, not a row: count the catch rows per key first, then keep the keys an anti-join finds in no unit, the region included.
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 orphan_catch(catch: pd.DataFrame, units: pd.DataFrame) -> pd.DataFrame: """One row per distinct catch key that matches no unit: the key (unit's names) and catch_rows.""" # Exercise 3.3: the task and examples are in the text above this cell. keys = catch.rename(columns={f"catch_{part}": part for part in PARTS}).groupby(KEY).size().rename("catch_rows").reset_index() return keys.merge(units[KEY], on=KEY, how="left_anti")Why each part is there
- Renaming
catch_operator_lineandcatch_unit_nolets both tables use one key list,KEY. Without it the join stops with KeyError: 'operator_line'. groupby(KEY).size()turns many catch rows into one row per key, and its count tells the editor whether one species or a whole unit's catch is astray.how="left_anti"keeps the keys with no match on the right.KEYstarts withregion_code, so a catch row of region 04 never matches a unit of region 01 that shares its household id.
Exercise 3.4. Every key and where it was found
The task
Why it matters: a key check reports both directions at once: how many keys matched, how many units have no catch, how many catch keys have no unit. One outer join with indicator=True gives all three, and the units with no catch are the list the next section starts from.
Input → output: the units and the catch table as stored → one row per distinct key of either table, with the key and status, one of three words:
| region_code | hh_id | operator_line | unit_no | status |
|---|---|---|---|---|
| 01 | 5101 | 1 | 1 | matched |
| 01 | 5101 | 2 | 1 | catch only |
| 01 | 5104 | 3 | 1 | unit only |
A unit entered twice is one key, so it is one row.
Tools: drop_duplicates(), merge(..., how="outer", indicator=True) and .map({...}), above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
Thousands of matched rows more than there are units |
The catch keys were not made distinct, so each species is a row. | step 2, drop_duplicates() |
| The small survey's household 5105 appears twice | The unit entered twice was not made distinct. | step 1 |
left_only and right_only in the result |
_merge not mapped to the three words. |
step 4, .map({...}) |
unit only and catch only swapped |
The tables in the other order: the left table is the units. | unit_keys.merge(catch_keys, ...) |
A column named _merge in the result |
It was kept after status was made. |
drop(columns="_merge") |
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
An outer join of the two tables' distinct keys keeps every key either side has, and its indicator says which side: one join for both directions.
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 key_status(units: pd.DataFrame, catch: pd.DataFrame) -> pd.DataFrame: """One row per distinct key of either table: the key and status (matched, unit only, catch only).""" # Exercise 3.4: the task and examples are in the text above this cell. unit_keys = units[KEY].drop_duplicates() catch_keys = catch.rename(columns={f"catch_{part}": part for part in PARTS})[KEY].drop_duplicates() both = unit_keys.merge(catch_keys, on=KEY, how="outer", indicator=True) both["status"] = both["_merge"].map({"both": "matched", "left_only": "unit only", "right_only": "catch only"}).astype(str) return both.drop(columns="_merge")Why each part is there
drop_duplicates()on both sides: catch keys repeat once per species, and a unit entered twice repeats its key. Without it the outer join multiplies them and every count is wrong.- The catch table's parts are renamed so both sides join
on=KEY, the region included. how="outer"keeps the keys found on one side only;indicator=Trueadds_merge, which says which side..map()turns pandas' words into the report's: with the units on the left,left_onlyis a unit with no catch.
Exercise 3.5. Leftovers paired, with their label
The task
Why it matters: the pairs are how an editor reads a key check household by household, and unit only, a unit whose catch is missing, is found nowhere else. The label in words reads without a legend.
Input → output: the orphan catch keys (Exercise 3.3's table) and the units with no catch (Exercise 3.4's unit only keys) → one row per pair, with the household, pair, the unit's two parts (suffix _unit), the catch's two parts (suffix _catch), and label:
| region_code | hh_id | pair | operator_line_unit | unit_no_unit | operator_line_catch | unit_no_catch | label |
|---|---|---|---|---|---|---|---|
| 01 | 5101 | 1 | 2 | 1 | catch only | ||
| 01 | 5102 | 1 | 1 | 1 | 2 | 3 | unit and catch |
| 01 | 5104 | 1 | 3 | 1 | unit only |
Number each side's rows within its household in key order, from 1.
Tools: sort_values, groupby(HOUSEHOLD).cumcount(), merge(..., how="outer", suffixes=(...)), and np.where, which picks a value by a condition; one np.where inside another picks from three.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
No catch only or unit only rows |
An inner join keeps only the pairs found on both sides. | how="outer" |
pair starts at 0 |
cumcount() counts from 0. |
+ 1 |
pair keeps growing across households |
Numbered over the whole table, not within each household. | groupby(HOUSEHOLD).cumcount() |
| The small survey's household 5108 pairs the other unit | The sides were not sorted by key before numbering. | sort_values(KEY) |
Columns operator_line_x and operator_line_y |
The default suffixes. | suffixes=("_unit", "_catch") |
Every one-sided pair is catch only |
The inner np.where tested the catch side, which is blank on those rows, instead of the unit side. |
step 4 |
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
Number each side's leftovers within the household, join the two sides on household and number, and say in words which sides came back: R's row_number() and full_join() in pandas.
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 pair_leftovers(orphans: pd.DataFrame, without_catch: pd.DataFrame) -> pd.DataFrame: """Leftovers paired by position within each household: the household, pair, the unit's and the catch's parts (suffixes _unit and _catch), and the label (unit and catch, unit only, catch only).""" # Exercise 3.5: the task and examples are in the text above this cell. unit_side = without_catch[KEY].sort_values(KEY) unit_side["pair"] = unit_side.groupby(HOUSEHOLD).cumcount() + 1 catch_side = orphans[KEY].sort_values(KEY) catch_side["pair"] = catch_side.groupby(HOUSEHOLD).cumcount() + 1 pairs = unit_side.merge(catch_side, on=HOUSEHOLD + ["pair"], how="outer", suffixes=("_unit", "_catch")) has_unit, has_catch = pairs["unit_no_unit"].notna(), pairs["unit_no_catch"].notna() pairs["label"] = np.where(has_unit & has_catch, "unit and catch", np.where(has_unit, "unit only", "catch only")) return pairsWhy each part is there
sort_values(KEY)beforecumcount()makes the numbering follow the key, so the same tables always give the same pairs.groupby(HOUSEHOLD).cumcount() + 1starts again at 1 in every household;cumcount()alone starts at 0.how="outer"keeps a leftover that has no counterpart at its position, which is whatunit onlyandcatch onlyreport. An inner join would keep only theunit and catchpairs.suffixes=("_unit", "_catch")keeps the two sides' parts apart: both tables name themoperator_lineandunit_no.- A side is present where its
unit_nois: the outer join fills an absent side with missing values. The innernp.wheredecides between the two one-sided labels once the outer one has taken the pairs.
Exercise 3.6. Which parts differ
The task
Why it matters: this is the step that turns "no match" into a correction. Knowing the part, the unit's value for it, and how many units are one part away is what lets a rule correct a typo and lets a person see at a glance why a key was referred.
Input → output: the orphan catch keys and the units → one row per orphan catch key and each distinct unit of its household, with the orphan's key, the unit's two parts (suffix _unit), and:
differs: the parts that differ, in key order, joined by", "("unit_no", or"operator_line, unit_no");n_differ: how many parts differ;n_units: how many units the household has (the rows this orphan has in the result);n_near: how many of them are one part away from the orphan.
| region_code | hh_id | operator_line | unit_no | operator_line_unit | unit_no_unit | differs | n_differ | n_units | n_near |
|---|---|---|---|---|---|---|---|---|---|
| 01 | 5101 | 2 | 1 | 1 | 1 | operator_line | 1 | 1 | 1 |
| 01 | 5102 | 2 | 3 | 1 | 1 | operator_line, unit_no | 2 | 1 | 0 |
| 01 | 5103 | 1 | 3 | 1 | 1 | unit_no | 1 | 2 | 2 |
| 01 | 5103 | 1 | 3 | 1 | 2 | unit_no | 1 | 2 | 2 |
An orphan whose household has no unit at all has no row: section 4 refers it to a person.
Tools: drop_duplicates(), merge(..., on=HOUSEHOLD, suffixes=("", "_unit"), validate="many_to_many"), comparisons with !=, .sum(axis=1) across columns, and groupby(KEY)[...].transform("size") and transform("sum") from Arrays & DataFrames.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
n_units and n_near are 2 for the small survey's household 5105 |
The unit entered twice was joined twice. | step 1, drop_duplicates() |
One row per orphan, every n_differ 2 or missing |
Joined on the whole key, which an orphan never matches. | on=HOUSEHOLD |
Columns operator_line_x and operator_line_y |
The default suffixes. | suffixes=("", "_unit") |
differs reads unit_no, operator_line |
The names in another order than the key's. | loop over PARTS |
n_units is the number of units in the survey |
transform("size") without the group. |
groupby(KEY) |
n_near equals n_units |
The rows were counted, not the rows one part away. | transform("sum") on n_differ == 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
Meet each stray key with every unit of its household, then compare part by part: the count of differing parts separates a typo from another unit, and the count of units one part away says whether the typo has one likely home.
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 compare_keys(orphans: pd.DataFrame, units: pd.DataFrame) -> pd.DataFrame: """Each orphan catch key beside each distinct unit of its household: the unit's parts (_unit), differs, n_differ, n_units and n_near.""" # Exercise 3.6: the task and examples are in the text above this cell. unit_keys = units[KEY].drop_duplicates() both = orphans[KEY].merge(unit_keys, on=HOUSEHOLD, suffixes=("", "_unit"), validate="many_to_many") differ = pd.DataFrame({part: both[part] != both[f"{part}_unit"] for part in PARTS}) both["differs"] = differ.apply(lambda row: ", ".join(part for part in PARTS if row[part]), axis=1) both["n_differ"] = differ.sum(axis=1) both["near"] = both["n_differ"] == 1 both["n_units"] = both.groupby(KEY)["near"].transform("size") both["n_near"] = both.groupby(KEY)["near"].transform("sum") return bothWhy each part is there
drop_duplicates()first: a unit entered twice would meet each orphan twice and make a household of one unit count as two, with two units one part away.on=HOUSEHOLDjoins each orphan to every unit of its household, which is the comparison position pairing could not make.validate="many_to_many"says the repeated rows are intended.suffixes=("", "_unit")keeps the orphan's parts under their own names and gives the unit's the_unitending.differis a table of True and False, one column per part;.sum(axis=1)counts the True values across each row, and the names of the True columns, in key order, makediffers.transformputs one figure per orphan key on every one of its rows:"size"counts the rows, which is the household's number of units, and"sum"on a True or False column counts the True ones, the units one part away.
Exercise 3.7. Automated or manual
The task
Why it matters: this table is the decision, one line per orphan. A reviewer reads its reasons; the next exercise turns its automated lines into edits.
Input → output: the comparison (Exercise 3.6's table) and the units with no catch → one row per orphan catch key, with its key and:
case:"automated"or"manual";reason: one of the four reasons in the rules above, as written there;operator_line_new,unit_no_new: the parts of the unit the rule chose, for an automated case; missing for a manual one.
| region_code | hh_id | operator_line | unit_no | case | reason | operator_line_new | unit_no_new |
|---|---|---|---|---|---|---|---|
| 01 | 5101 | 2 | 1 | automated | one part from one unit | 1 | 1 |
| 01 | 5102 | 2 | 3 | automated | only stray key, only unit without catch | 1 | 1 |
| 01 | 5103 | 1 | 3 | manual | one part from two or more units | ||
| 01 | 5109 | 3 | 2 | manual | both parts differ |
Tools: merge(..., how="left", indicator=True), groupby().size(), transform("any"), np.select, np.where, drop_duplicates().
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
Household 5102 of the small survey is manual, both parts differ |
Rule 1 was not tested, or tested after the default case. | steps 1 to 3, and rule 1 first |
Household 5108 of the small survey is only stray key, only unit without catch |
The units without catch were not counted: 5108 has two, so rule 1 does not hold. | step 2, idle == 1 |
| Two rows for the same orphan key | The rows of a household of several units were not reduced to one. | step 6, drop_duplicates(KEY) |
| Household 5103's orphan is automated | n_differ == 1 on the row tested instead of n_near, the units one part away. |
rules 2 and 3 use n_near |
| An automated row with missing new parts, or the parts of the wrong unit | The correction taken from the first row of the orphan, not from the row the rule chose. | step 5 |
| ValueError: list of cases must be same length as list of conditions | Three conditions, but two or four choices. | np.select's two lists |
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
The four rules as one np.select, tested in order, on facts that hold for the whole orphan key; an automated case then takes its correction from the one row that names the chosen unit, and a manual one takes none.
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 decide(comparison: pd.DataFrame, without_catch: pd.DataFrame) -> pd.DataFrame: """One row per orphan catch key: case (automated or manual), reason, and the new parts for an automated case.""" # Exercise 3.7: the task and examples are in the text above this cell. lonely = without_catch[KEY].drop_duplicates().rename(columns={part: f"{part}_unit" for part in PARTS}) table = comparison.merge(lonely, on=HOUSEHOLD + [f"{part}_unit" for part in PARTS], how="left", indicator=True) table["no_catch"] = table["_merge"] == "both" strays = comparison[KEY].drop_duplicates().groupby(HOUSEHOLD).size().rename("strays").reset_index() idle = lonely.groupby(HOUSEHOLD).size().rename("idle").reset_index() table = table.merge(strays, on=HOUSEHOLD, how="left").merge(idle, on=HOUSEHOLD, how="left") table["pair_row"] = (table["strays"] == 1) & (table["idle"] == 1) & table["no_catch"] table["paired"] = table.groupby(KEY)["pair_row"].transform("any") table["reason"] = np.select( [table["paired"], table["n_near"] == 1, table["n_near"] >= 2], [PAIRED, ONE_NEAR, SEVERAL_NEAR], default=NONE_NEAR, ) table["case"] = np.where(table["reason"].isin([PAIRED, ONE_NEAR]), "automated", "manual") chosen = ((table["reason"] == PAIRED) & table["pair_row"]) | ((table["reason"] == ONE_NEAR) & (table["n_differ"] == 1)) fixes = table.loc[chosen, KEY + [f"{part}_unit" for part in PARTS]].rename(columns={f"{part}_unit": f"{part}_new" for part in PARTS}) return table.drop_duplicates(KEY)[KEY + ["case", "reason"]].merge(fixes, on=KEY, how="left").reset_index(drop=True)Why each part is there
- Renaming
without_catch's parts to the_unitnames lets the left join match each row's unit;indicator=Truemarks the units found there, the ones with no catch. A left join keeps every row of the comparison. - Rule 1 is about the household: one stray key and one unit without catch. Counting each with
groupby(HOUSEHOLD).size()and merging the counts back puts them on every row;how="left"keeps a household that has no unit without catch, whose count stays blank and is not 1. transform("any")makes rule 1 hold on every row of the stray key, not only on the row of its unit, sonp.selectgives all of its rows one reason.np.selecttakes the first condition that holds, ascase_when()andCASE WHENdo. Rule 1 comes first, so a pair whose parts both differ is still corrected, and rule 2 comes before rule 3, which takes the keys with more than one near unit.- An orphan has one row per unit of its household, and only one of them names the unit the rule chose. Keeping that row's parts, and merging them back with
how="left", leaves a manual case with no new value. drop_duplicates(KEY)after the reason is set: every row of an orphan has the same case and reason, so any one of them speaks for it.
Exercise 3.8. The edits table
The task
Why it matters: this is the table a reviewer signs off and the write-back applies. If it names the unit's columns instead of the catch table's, or one row per key instead of one per catch row, the write-back changes the wrong thing or too little.
Input → output: the decisions (Exercise 3.7's table) and the catch table as stored → one row per catch row and part that changes, for the automated cases only:
| region_code | hh_id | table | row_id | column | old | new | reason |
|---|---|---|---|---|---|---|---|
| 01 | 5101 | catch | 3 | catch_operator_line | 2 | 1 | one part from one unit |
| 01 | 5102 | catch | 4 | catch_operator_line | 2 | 1 | only stray key, only unit without catch |
| 01 | 5102 | catch | 4 | catch_unit_no | 3 | 1 | only stray key, only unit without catch |
| 01 | 5102 | catch | 5 | catch_operator_line | 2 | 1 | only stray key, only unit without catch |
| … | … | … | … | … | … | … | … |
table is CATCH; row_id is the catch row's row_id.
Tools: a boolean filter, merge(left_on=..., right_on=...), a loop over PARTS, and pd.concat.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
column reads unit_no |
The unit's name, which the catch table does not have. | f"catch_{part}" |
| One edit per key, not per catch row | The decisions were not joined back to the catch rows. | step 2 |
Edits for manual keys, with missing new |
The automated cases were not kept first. | step 1 |
Rows where old equals new |
Every part listed, not only the ones that change. | != in step 3 |
row_id repeats with different households |
Rows from two regions: each region's database numbers its rows from 1. | keep region_code |
| KeyError: 'catch_operator_line' | The catch table was renamed before the join. | use the catch table as stored |
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 decision names a key; the database needs rows. Joining the decisions back to the catch rows that carry each key, then listing each part that changes, gives one edit per value, in the database's own names.
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 edits_table(decisions: pd.DataFrame, catch: pd.DataFrame) -> pd.DataFrame: """One row per catch row and key part an automated decision changes: region_code, hh_id, table, row_id, column, old, new and reason.""" # Exercise 3.8: the task and examples are in the text above this cell. automated = decisions[decisions["case"] == "automated"] rows = automated.merge(catch, left_on=KEY, right_on=HOUSEHOLD + [f"catch_{part}" for part in PARTS]) edits = [] for part in PARTS: changed = rows[rows[f"catch_{part}"] != rows[f"{part}_new"]] edits.append(pd.DataFrame({ "region_code": changed["region_code"], "hh_id": changed["hh_id"], "table": CATCH, "row_id": changed["row_id"], "column": f"catch_{part}", "old": changed[f"catch_{part}"], "new": changed[f"{part}_new"], "reason": changed["reason"], })) return pd.concat(edits, ignore_index=True)Why each part is there
- Only automated decisions make edits; a manual one waits for a person.
left_on=KEYandright_onthe catch's prefixed parts finds every catch row that carries the orphan key, so a unit whose five catch rows all point elsewhere gets five edits per part, not one.columnis the part withcatch_in front, the catch table's name for it. The write-back runsUPDATE ... SET catch_unit_no = ...; a name without the prefix is a column the table does not have.- A part whose value already equals the unit's is no edit, so each table keeps only the rows where
old != new. row_idis the row's id in its region's database. Each region's database numbers its rows from 1, so a row id repeats between regions, which is whyregion_codestays in the table.
Exercise 3.9. The dry run: what would change
The task
Why it matters: the dry run is what a reviewer reads before saying yes, and what the write itself checks before it touches a row. It reads the database and changes nothing.
Input → output: an open DuckDB connection to one region's database and an edits table → the edits table with two columns added:
now: the value the row holds now, or missing if the row is not there;status:"already edited"if the row's audit flag is 1; else"will change"ifnowequalsold; else"conflict"(the row is missing, or holds another value).
| row_id | column | old | new | now | status |
|---|---|---|---|---|---|
| 2 | catch_operator_line | 2 | 1 | 1 | already edited |
| 3 | catch_operator_line | 2 | 1 | 2 | will change |
| 3 | catch_unit_no | 3 | 1 | 4 | conflict |
First, the region: read region_code from the database's household table. If any edit's region_code is another region, raise ValueError(...) with a message that names both. Compare the regions as numbers: region 04's database stores "04" as text, the other two store 1 and 7 as numbers, and int() reads both.
A table that has never been written has no audit column yet: read NULL in its place (columns_of tells you which).
Tools: con.execute(sql, [values]).fetchall() and .fetchone() (module 2), edits.to_dict("records") for a loop over the edits, and columns_of, above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
Region 04's edits against region 01's database get a table, not refused |
The region was not checked, so row ids of another region's file were read. | step 1 |
Region 04's own database is refused |
"04" compared with 4: text against a number. |
int() on both sides |
Row 2 of the partly edited database is conflict |
The value was tested before the flag; an edited row holds the new value. | test the flag first |
| BinderException: Binder Error: Referenced column "key_corrected" not found in FROM clause! | The audit column read from a table that does not have it yet. | NULL when columns_of lacks it |
| TypeError: cannot unpack non-iterable NoneType object | fetchone() gave None for a missing row. |
test found is None first |
| InvalidInputException: Invalid Input Error: Values were not provided for the following parameters: 1 | The ? in the query, but no list of values after it. |
[edit["row_id"]] |
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
Before any write, read what each edit would touch: the row's current value and its audit flag decide whether the edit will change it, was done before, or no longer fits the database.
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 plan_write(con: duckdb.DuckDBPyConnection, edits: pd.DataFrame) -> pd.DataFrame: """The dry run: the edits with now (the row's current value) and status (will change, already edited, conflict). Refuses edits for another region with a ValueError.""" # Exercise 3.9: the task and examples are in the text above this cell. in_database = {int(row[0]) for row in con.execute("SELECT DISTINCT region_code FROM household").fetchall()} in_edits = {int(region) for region in edits["region_code"]} if not in_edits <= in_database: raise ValueError(f"edits for region {sorted(in_edits - in_database)} cannot be written to the database of region {sorted(in_database)}") now, status = [], [] for edit in edits.to_dict("records"): table = edit["table"] flag = AUDIT if AUDIT in columns_of(con, table) else "NULL" found = con.execute(f'SELECT "{edit["column"]}", {flag} FROM "{table}" WHERE row_id = ?', [edit["row_id"]]).fetchone() if found is None: now.append(None) status.append("conflict") continue value, flagged = found now.append(value) status.append("already edited" if flagged == 1 else "will change" if value == edit["old"] else "conflict") return edits.assign(now=now, status=status)Why each part is there
- The region check comes first: household ids and row ids repeat between the regional databases, so an edit of region 04 read in region 01's file would find another household's row and report it as a fine edit.
int()on both sides compares region 04's text"04"and region 01's number1as the numbers they are.raise ValueError(...), notassert: anassertdisappears when Python runs with-O, and the refusal with it.- The
?placeholder takes the row id from the list, so a value in the edits can never change the statement. Table and column names cannot be placeholders, so they come from the edits table, which the code builds itself. - A table without the audit column has never been written by this step, so its flag reads as
NULL, andSELECT ..., NULLkeeps one query for both cases. - The flag is tested before the value: an edited row holds the new value, so "now equals old" would call it a conflict.
Exercise 3.10. The write, all or nothing
The task
Why it matters: this is the one step in the module that changes a database. Everything before it can be run any number of times; this one is safe to run more than once only because of how it is written.
Input → output: the path of a region's database file, an edits table, and apply (default False) → the dry run's table, with "will change" read as "changed" when the edits were written.
apply=False(the default): open the file read-only (duckdb.connect(str(database), read_only=True)) and returnplan_write's table. Nothing is written.apply=True: open it for writing, and in one transaction: plan again; if any edit is aconflict,raise ValueError(...); add the audit column to each table you change (ALTER TABLE ... ADD COLUMN IF NOT EXISTS key_corrected INTEGER); run oneUPDATEperwill changeedit, setting the column and the flag;COMMIT. On any error,ROLLBACK, then raise the error again.
Open the file with with duckdb.connect(...) as con: so it is closed when the function returns, even after an error: a file still open in one connection cannot be opened again with other settings.
| run | statuses it returns |
|---|---|
write_back(path, edits) |
will change ×5, nothing written |
write_back(path, edits, apply=True) |
changed ×5 |
write_back(path, edits, apply=True) again |
already edited ×5, nothing written |
Tools: plan_write (Exercise 3.9), and this transaction shape (Python for Data Management teaches it too):
con.execute("BEGIN TRANSACTION")
try:
... # plan, refuse on conflict, add the column, update
con.execute("COMMIT")
except Exception:
con.execute("ROLLBACK") # undo everything since BEGIN
raise # and let the caller know
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| The dry run changed the table | The dry run wrote, or the file was opened for writing and changed. | read_only=not apply, and return before BEGIN |
write again says changed |
The second run did not skip flagged rows. | plan_write's already edited |
After a refusal, the table has a key_corrected column |
The ALTER TABLE ran outside the transaction, or no ROLLBACK. |
BEGIN before the ALTER |
refused: RuntimeError |
The conflict raised another kind of error. | raise ValueError(...) |
| ConnectionException: Connection Error: Can't open a connection to same database file with a different configuration than existing connections | A connection to the file was left open. | with duckdb.connect(...) as con: |
| TransactionException: TransactionContext Error: cannot start a transaction within a transaction | An earlier failed run left a transaction open, because ROLLBACK was missing. |
except Exception: ROLLBACK; raise |
| Only one of a row's two parts changed | The flag was required to be empty in the UPDATE, and the first part's update set it. |
update every will change edit; plan once |
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 dry run unless told otherwise; when told, one transaction that refuses a stale plan, flags every row it changes, and skips every row already flagged, so a second run changes nothing.
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 write_back(database, edits: pd.DataFrame, apply: bool = False) -> pd.DataFrame: """Write the edits into a region's database file, all or nothing, flagging each edited row. apply=False (the default) is a dry run: it reads the file and writes nothing.""" # Exercise 3.10: the task and examples are in the text above this cell. with duckdb.connect(str(database), read_only=not apply) as con: if not apply: return plan_write(con, edits) con.execute("BEGIN TRANSACTION") try: plan = plan_write(con, edits) if (plan["status"] == "conflict").any(): raise ValueError(f"{(plan['status'] == 'conflict').sum()} edits no longer fit the database: make the edits table again") todo = plan[plan["status"] == "will change"] for table in todo["table"].unique(): con.execute(f'ALTER TABLE "{table}" ADD COLUMN IF NOT EXISTS {AUDIT} INTEGER') for edit in todo.to_dict("records"): con.execute(f'UPDATE "{edit["table"]}" SET "{edit["column"]}" = ?, {AUDIT} = 1 WHERE row_id = ?', [edit["new"], edit["row_id"]]) con.execute("COMMIT") except Exception: con.execute("ROLLBACK") raise return plan.assign(status=plan["status"].replace({"will change": "changed"}))Why each part is there
read_only=not apply: the dry run opens the file so that no statement can change it, whatever the code below does.applydefaults toFalse, so writing takes a deliberateapply=True. A step that changes a shared database defaults to the dry run; a step whose output is easy to remake can default to writing.- Planning again inside the transaction reads the rows as they are at the moment of writing, not as they were when the dry run was shown.
- One conflict refuses the whole write: the edits table was made from another state of the database, and part of it may be wrong.
- DuckDB keeps
ALTER TABLEinside the transaction, so a refused write leaves no audit column behind. (On a MySQL server,ALTER TABLEcommits the open transaction: add the column once, before the transaction.) ROLLBACKthenraise: the database goes back to where it was, and the caller still learns why.- A flagged row's status is
already edited, so the second run updates nothing: running twice equals running once.