Skip to content
Learn Python with BNHR

Edit rules and duplicates

On this page
  1. Overview
  2. 4.1 · The codes in a codebook entry
  3. 4.2 · A frequency table against the valid codes
  4. 4.3 · The tonnage B3 expects
  5. 4.4 · A unit's scale from its boats
  6. 4.5 · The runner
  7. 4.6 · Edits by specification
  8. 4.7 · Every copy of a repeated key
  9. 4.8 · More than one distinct value within a group

Every exercise in 30_edit_rules.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 4.1. The codes in a codebook entry

The task

Why it matters: the codebook is where the valid codes are written once. A frequency table that reads them from it stays right when the codebook changes; one that types them again drifts.

Input → output: one cell of the codebook's values column → a dictionary {code: label} with the codes as integers, in the codebook's order; {} when the text lists no codes or the cell is empty:

values result
1 = Male; 2 = Female {1: "Male", 2: "Female"}
1 = Yes; 0 = No; asked of members 10 years old and over {1: "Yes", 0: "No"}
blank if unit_uses_boat = 0 {}
(empty: a missing value) {}

Tools: isinstance(values, str), text.split(";"), part.partition("=") (splits at the first = into the left side, the = and the rest, and gives an empty = when there is none), .strip(), .isdigit(), int().

If the check is red: common causes

what you see the usual cause look at
AttributeError: 'float' object has no attribute 'split' The empty cell is a missing value, not text. isinstance(values, str) first
[['1', 'Male'], ...], with quotes The codes are kept as text. int(code)
[[' 1', 'Male'], ...] or labels starting with a space The parts were not stripped. .strip() on both sides
A code from blank if unit_uses_boat = 0 Every part with = was kept. keep a part only if the left side .isdigit()
ValueError: invalid literal for int() int() was tried on words. test .isdigit() before int()
No 0: 'No' The test was if int(code), and 0 counts as false. test .isdigit(), not the number

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 4.2. A frequency table against the valid codes

The task

Why it matters: this is the table an editor reads first for every coded item. Codes outside the list are the errors; valid codes with no answers are worth a look (a skip pattern that never fires, a code nobody was trained on); blanks are counted so they can be explained.

Input → output: a column of codes (with blanks) and the valid codes as {code: label} → a table with the columns code, label and count, and these rows, in this order:

  1. every valid code, in the dictionary's order, with its label and its count, 0 included;
  2. every code in the column that the dictionary does not have, smallest first, each with the label Invalid value;
  3. one last row, code missing (None), label No answer, the number of blanks (0 included).
code label count
1 Yes 1
0 No 2
8 Don't know 0
3 Invalid value 2
7 Invalid value 1
None No answer 1

That table is for the codes 0, 1, blank, 7, 3, 0, 3 and the valid codes {1: "Yes", 0: "No", 8: "Don't know"}.

Tools: value_counts() (it leaves blanks out by default), counts.get(code, 0), sort_index(), isna().sum(), a list of rows and pd.DataFrame(rows, columns=[...]).

If the check is red: common causes

what you see the usual cause look at
No row for 8 Don't know The rows were built from the counts, so an unused code has none. loop over valid and use counts.get(code, 0)
One Invalid value row with the total The invalid codes were added up. one row per invalid code
No No answer row, or a blank listed as an invalid code value_counts(dropna=False) put the blanks among the codes. value_counts(), and blanks counted with isna().sum()
The invalid codes as 3, 7 in the wrong order, or 7 first They are in the order of their counts. counts.sort_index()
count of 0 for every valid code The dictionary's keys are text and the codes numbers. the keys must be integers, as Exercise 4.1 gives them

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 4.3. The tonnage B3 expects

The task

Why it matters: a stored computation is only as right as the program that wrote it. Computing it again from the answers it came from is the check, and, when they disagree, the correction (section 5).

Input → output: the boats table → a Series, one value per boat in the boats' order: the tonnage B3 expects, by how the boat's size is known, and missing for a boat with a dimension missing or with no boat_measured_in:

boat_measured_in boat_length, beam, depth boat_tonnage_reported expected tonnage
2 (meters) 10.0, 1.2, 0.6 10.0 × 1.2 × 0.6 × 0.212 = 1.5264
3 (feet) 30, 4, 2 30 × 4 × 2 × 0.006 = 1.44
1 (papers) 4.2 4.2
2 (meters) 8.0, 1.1, blank missing
blank 9.0, 1.2, 0.6 missing

Tools: column arithmetic, and case_when started from a Series of missing values (pd.Series(np.nan, index=boats.index)), with conditions built by isin, which section 1 showed never to be missing.

If the check is red: common causes

what you see the usual cause look at
Missing for the boat sized from its papers The papers' case is not there; B3 expects boat_tonnage_reported for it. a third condition, isin([1])
A value for the boat measured in feet that is about 35 times too large The meters factor used on feet, or the other way round. 0.212 for meters, 0.006 for feet
A value for the boat with no boat_measured_in case_when was started from the meters value, or a condition used ==, whose <NA> counts as met. start from np.nan; build conditions with isin
Every value missing The conditions test 1, 2, 3 against the wrong codes: 1 is the papers, 2 meters, 3 feet. the codebook's boat_measured_in
ValueError about lengths A list was given to case_when instead of (condition, value) pairs. [(condition, value), ...]

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 4.4. A unit's scale from its boats

The task

Why it matters: a unit's scale (unit_scale) decides whether it is counted with the small-scale or the large-scale units, the first split of every fisheries table. U3 says the scale follows the boats: 2 if any boat is 5.0 gross tons or more, 1 otherwise.

Input → output: the unit table and the boat table → the unit table, its rows unchanged, with two new columns:

  • largest_tonnage: the largest boat_tonnage among the unit's boats; missing for a unit with no boat;
  • scale_by_boats: 2 where largest_tonnage is 5.0 or more, 1 otherwise, including a unit with no boat.

A unit is named by UNIT_KEY, its region, household and two key parts: region_code, hh_id, operator_line, unit_no.

region_code hh_id … unit_scale boats' tonnage largest_tonnage scale_by_boats
01 5300 … 1 1.2, 0.8 1.2 1
04 5300 … 1 5.5 5.5 2
01 5301 … 1 no boat missing 1
01 5302 … 2 5.0 5.0 2

Tools: groupby(UNIT_KEY)["boat_tonnage"].max(), a left merge with validate="many_to_one", and np.where(condition, 2, 1).

If the check is red: common causes

what you see the usual cause look at
Region 04's unit of household 5300 has largest_tonnage 1.2, or both have 5.5 The region is not in the key. group and join on all of UNIT_KEY
The unit with no boat is missing An inner join. how="left"
The unit with no boat is scale 2 The condition was written as largest_tonnage < 5 for 1: a missing value makes it False. np.where(largest_tonnage >= 5, 2, 1)
The boat of exactly 5.0 makes its unit scale 1 > used; the code says 5.0 or more. >= 5
More rows than units The boats were joined without the max, one row per boat. reduce the boats to one row per unit first

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 4.5. The runner

The task

Why it matters: this function is the whole of the rule machinery. Every rule written as a row of the table goes through it, so it is written once and tested once; the rules themselves are only data.

Input → output: the specification table, the tables by name (frames), and the named values (rule_values) → the failure report above. For each rule:

  1. take its table from frames; keep the rows applies_to picks (table.query(applies_to, local_dict=rule_values)), or every row when applies_to is empty text or missing;
  2. evaluate must_hold on them (.eval(must_hold, local_dict=rule_values)); a row fails where the result is False or missing;
  3. count the failing rows per household, and add the rule's rule, table, action and message.
rule table region_code hh_id rows action message
A1 people 01 5300 2 refer sex is 1 or 2
A2 people 04 5300 1 refer a member who runs a unit is 16 or older

A rule with no failures adds no row; a spec with no failures at all gives an empty report with the seven columns.

Tools: spec.itertuples(index=False) (each row as an object: rule.must_hold), query and eval with local_dict=, fillna(False), groupby(HOUSEHOLD).size(), assign, pd.concat, sort_values, reset_index(drop=True).

If the check is red: common causes

what you see the usual cause look at
No A3 row for the member with a blank age ~holds kept <NA>, and the filter dropped it. holds.fillna(False)
A2 fails the 12-year-old who does not run a unit The scope was not applied. table.query(rule.applies_to, ...) first
ValueError or AttributeError on A3's scope A missing applies_to (as from a CSV) was given to query. use every row unless it is non-empty text
UndefinedVariableError: local variable 'valid' is not defined @valid has nothing to look up. local_dict=values in both query and eval
One row for household 5300 with rows 3 Grouped by hh_id alone: regions 01 and 04 together. groupby(HOUSEHOLD)
One row per failing member, not per household The failing rows were not counted per household. groupby(HOUSEHOLD).size()
ValueError: No objects to concatenate found is empty: the loop never appended. append inside the loop

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 4.6. Edits by specification

The task

Why it matters: this is the edit step as a program. The specification says what to edit and how, one function makes every edit the same way, and its log is what a supervisor reads and what the next run is compared with.

Input → output: the specification table with variable and edit_to, the tables by name, the named values (rule_values) and a seed → a pair: the tables with the edits made, and the edit log. Make one generator at the start, rng = np.random.default_rng(seed). Then, for each rule whose edit_to is text that is not empty, in the specification's order:

  1. take its failing rows from the edited tables with failures, sorted by region_code and the row id, row_id;
  2. find the new values: if drawn_from(rule.edit_to) gives codes, draw one per failing row with rng.choice(codes, size=len(failing)); otherwise evaluate failing.eval(rule.edit_to, local_dict=values);
  3. write one log row per failing row, then write the new values into the rule's variable on those rows, in the column's own type (.astype(table[rule.variable].dtype)).

The log has the columns EDIT_LOG_COLUMNS: rule, table, region_code, hh_id, row (the row id), variable, before and after written with as_text, and how: the rule's edit_to, with , seed 41593 added after a draw (the seed you were given). The tables you are given stay as they are: edit copies.

rule table region_code hh_id row variable before after how
U4 fishing_unit 01 5300 1 unit_uses_boat 1 (boat_rows > 0) * 1
U7 fishing_unit 07 5087 1 unit_boats 1 2 boat_rows
W1 crew 01 5300 1 crew_sex 3 1 or 2, as drawn random(1, 2), seed 41593
B2 boat 01 5300 1 boat_engine 0 2 2

Tools: {name: table.copy() for name, table in frames.items()}, np.random.default_rng(seed), rng.choice, DataFrame.eval, pd.Series(new, index=failing.index) (a single value or one value per row, lined up with the failing rows), failing.iterrows(), .astype(dtype), .loc[rows, column] = values.

If the check is red: common causes

what you see the usual cause look at
Red only for "rows in another order" The draws follow the rows' order as they arrived. sort the failing rows by region_code and the row id before drawing
Red for the first case; region 04's row 1 and region 01's row 1 swap codes Sorted by the row id alone: row ids repeat across regions. sort by ["region_code", ROW_ID]
No U7 row for region 07's unit 1 U7's failures were taken from the tables you were given, where that unit's unit_uses_boat is still blank. failures on edited[rule.table]
the tables given are unchanged is False The edits were written into the tables you were given. table.copy() for every table first
A different code on every run The generator has no seed, or np.random.choice was used. np.random.default_rng(seed)
Red for "another seed" only The seed is typed in, not the one passed. use the seed argument, in the generator and in how
before is <NA>, or before equals after str() on a blank, or the value read after it was written. as_text(row[rule.variable]) before Step 5
ValueError: expr cannot be an empty string, or a log row for B1 A rule with no edit was applied: B1 only refers. skip a rule whose edit_to is empty
ValueError: Length of values rng.choice drew a number of codes other than the number of failing rows. size=len(failing)
TypeError: Invalid value ... for dtype 'int32', on the survey only The new values are 64-bit integers and the survey's boat_engine is 32-bit; pandas will not change a column's type in a partial write. new.astype(table[rule.variable].dtype) in Step 5

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 4.7. Every copy of a repeated key

The task

Why it matters: to decide what to do with a duplicate, an editor sees all its copies side by side. duplicated() marks the second copy only; keep=False marks every copy.

Input → output: a table and a key (a list of columns) → the rows whose key, with no part blank, appears more than once, every copy kept, sorted by the key:

region_code hh_id boat_no boat_reg_no
01 5300 1 R01-00101 kept: the registration is on two rows
01 5300 3 R01-00101 kept
01 5300 2 blank left out: not registered
01 5300 4 blank left out
01 5301 1 R01-00101 left out: another household, the boat sold

Tools: dropna(subset=key), duplicated(subset=key, keep=False), sort_values(key).

If the check is red: common causes

what you see the usual cause look at
The two boats with no registration are listed Blank key parts count as equal in duplicated. dropna(subset=key) first
One row per repeated key, not two duplicated() marks the second copy only. keep=False
Household 5301's boat is listed The key passed had no household, or the household was dropped from it. use the key as given: it starts with region_code and hh_id
Hundreds of boats Both of the above: blanks kept and every copy marked. dropna, then duplicated(keep=False)
KeyError with a column name The key was given as one text, not a list. subset=key, where key is a list

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 4.8. More than one distinct value within a group

The task

Why it matters: both definitions are one question asked of other columns: which groups hold more than one distinct value of an item. One function answers both, and what it returns is the list a person checks.

Input → output: a table, the columns that make a group (within) and the columns to count (counted) → one row per group in which any counted column has more than one distinct value: the within columns, then each counted column holding its number of distinct values. Rows sorted by within, numbered from 0. A blank is not a value: nunique() leaves it out, and groupby leaves out a group whose key is blank. For the registered boats of four households, within = [*HOUSEHOLD, "boat_reg_no"] and counted = ["operator_line", "unit_no"]:

region_code hh_id boat_reg_no operator_line unit_no
01 5300 R01-00101 1 1 one operator's two units
01 5300 R01-00101 1 2
01 5301 R01-00102 1 1 two operators' units
01 5301 R01-00102 2 1
01 5302 R01-00103 1 1 one row, stored twice
01 5302 R01-00103 1 1
04 5300 R04-00101 1 1 one boat, in another region

gives

region_code hh_id boat_reg_no operator_line unit_no
01 5300 R01-00101 1 2
01 5301 R01-00102 2 1

Tools: groupby(within)[counted].nunique(), reset_index(), (counts[counted] > 1).any(axis=1), sort_values(within), reset_index(drop=True).

If the check is red: common causes

what you see the usual cause look at
Household 5302 is listed, with 2 and 2 Rows were counted, not distinct values: size() or count(). nunique()
Household 5300 of region 01 is missing Both counts had to be over 1: .all, or &. the definition says or: .any(axis=1)
Household 5300 has 3 units, or region 04 is missing Grouped by hh_id alone, so two regions became one household. group by within as given; it starts with region_code
A row for the stratum F household, with a blank sel_ea groupby(..., dropna=False) kept the blank area as a group. groupby's default leaves a blank key out
Every group is listed, with its counts The groups were not filtered. keep the rows where a count is over 1
KeyError with a column name A column name typed instead of the within and counted lists. use the arguments

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 debugging drill
Debugging drill D2Debugging drill: a detector that flags the wrong rows
AboutDebugging drill D2 of Python for Survey Statistics, after module 9: six bugs that make an anomaly detector flag the wrong rows, to predict, trace, fix and explain.
CoursePython for Survey Statistics, free