Skip to content
Learn Python with BNHR

Match the keys

On this page
  1. Overview
  2. 3.1 · The orphans of any child table, by its prefix
  3. 3.2 · Operators against the roster
  4. 3.3 · Catch keys with no unit
  5. 3.4 · Every key and where it was found
  6. 3.5 · Leftovers paired, with their label
  7. 3.6 · Which parts differ
  8. 3.7 · Automated or manual
  9. 3.8 · The edits table
  10. 3.9 · The dry run: what would change
  11. 3.10 · The write, all or nothing

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.

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's operator_line;
  • "operator not flagged": the line is there, and its mem_role_operator is not 1 (0 or blank);
  • "count differs": the line is flagged, and its mem_units_run is 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.

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.

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.

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.

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.

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.

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.

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" if now equals old; 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.

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 return plan_write's table. Nothing is written.
  • apply=True: open it for writing, and in one transaction: plan again; if any edit is a conflict, raise ValueError(...); add the audit column to each table you change (ALTER TABLE ... ADD COLUMN IF NOT EXISTS key_corrected INTEGER); run one UPDATE per will change edit, 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.

Something new

Identify results
LayerExplore a module
ModuleAnomalies by rule and by statistics
AboutModule 8 of Python for Survey Statistics: invalid, implausible and unusual values, outliers within groups with IQR, robust z and Hidiroglou-Berthelot, interviewer indicators, and one ranked review table. Its sections, its notebooks to read on the web, and the companion's solutions and explanations.
CoursePython for Survey Statistics, free