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.
The idea
A code list is a run of "code = label" parts between semicolons; a part is a code only when the left of its first "=" is a whole number.
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 codebook_codes(values) -> dict: """The codes a codebook `values` entry lists, as {code: label} with integer codes, in its order; {} if it lists none.""" # Exercise 4.1: the task and examples are in the text above this cell. codes = {} if not isinstance(values, str): return codes for part in values.split(";"): code, equals, label = part.partition("=") if equals and code.strip().isdigit(): codes[int(code)] = label.strip() return codesWhy each part is there
isinstance(values, str)first: an empty cell of the CSV is read as a missing value (a float), and.spliton it would raise AttributeError.split(";")thenpartition("=")cuts each part at its first=, so a label that contains=keeps the rest whole.code.strip().isdigit()is the test that the part is a code: it refuses the noteasked of members 10 years old and over(no=) andblank if unit_uses_boat = 0(its left side is words). The code0passes it:"0".isdigit()isTrue.int(code)makes the key a number. The survey stores codes as integers, so a dictionary keyed by the text"1"would match none of them.
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:
- every valid code, in the dictionary's order, with its label and its count, 0 included;
- every code in the column that the dictionary does not have, smallest first, each with the label
Invalid value; - one last row, code missing (
None), labelNo 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.
The idea
Read the column against the list, not the list against the column: every valid code gets a row whether or not it was used, every other code gets a row of its own marked invalid, and the blanks get theirs.
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 code_frequency(values: pd.Series, valid: dict) -> pd.DataFrame: """The frequency table of a coded column against its valid codes: code, label, count; invalid codes, then blanks.""" # Exercise 4.2: the task and examples are in the text above this cell. counts = values.value_counts() rows = [(code, label, int(counts.get(code, 0))) for code, label in valid.items()] rows += [(code, "Invalid value", int(count)) for code, count in counts.sort_index().items() if code not in valid] rows.append((None, "No answer", int(values.isna().sum()))) return pd.DataFrame(rows, columns=["code", "label", "count"])Why each part is there
value_counts()counts each code once and leaves blanks out, so the codes in it are all real values.- Looping over
valid, not overcounts, gives every valid code a row in the codebook's order, withcounts.get(code, 0)writing 0 for a code nobody used. A table built fromcountsalone would never show that a valid code is missing. - A code in
countsbut not invalidis invalid. Each keeps its own row, so the editor sees which codes are wrong, 3 and 7, not only how many. - The blanks are counted with
isna(), apart from the invalid codes: a blank may be a skip the questionnaire asks for, an invalid code never is.
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.
The idea
Compute the volume once for every boat, then let the way the boat's size is known pick the factor, or the papers' figure; a boat that fits no case keeps the missing value it started with.
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 tonnage_expected(boats: pd.DataFrame) -> pd.Series: """Each boat's gross tonnage as rule B3 states it: L × B × D × 0.212 in meters, × 0.006 in feet, the papers' figure for a boat whose size comes from its papers; missing otherwise.""" # Exercise 4.3: the task and examples are in the text above this cell. volume = boats["boat_length"] * boats["boat_beam"] * boats["boat_depth"] measured = boats["boat_measured_in"] return pd.Series(np.nan, index=boats.index).case_when([ (measured.isin([2]), volume * 0.212), (measured.isin([3]), volume * 0.006), (measured.isin([1]), boats["boat_tonnage_reported"]), ])Why each part is there
- One product of the three dimensions serves both units: only the factor differs. A boat sized from its papers has blank dimensions, so its volume is missing and is never chosen.
- The factors are the survey's: 0.212 per cubic meter, 0.006 per cubic foot. Swapped, every expected tonnage is wrong by a factor of 35, and B3 would flag every measured boat.
case_whenon a Series ofnp.nanleaves a boat with noboat_measured_inmissing, so B3 cannot pass it. Started from the meters value instead, every boat not measured in feet or sized from papers would get one.isin([2])isFalsefor a blankboat_measured_in;== 2would be<NA>, which pandas'case_whencounts as met.
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 largestboat_tonnageamong the unit's boats; missing for a unit with no boat;scale_by_boats: 2 wherelargest_tonnageis 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.
The idea
Reduce the boats to one number per unit, the largest tonnage, bring it into the unit table, and derive the scale the rule says the unit should have.
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 scale_from_boats(units: pd.DataFrame, boats: pd.DataFrame) -> pd.DataFrame: """The unit table with largest_tonnage (its boats' largest boat_tonnage; missing if none) and scale_by_boats (2 if 5.0 or more, else 1).""" # Exercise 4.4: the task and examples are in the text above this cell. largest = boats.groupby(UNIT_KEY)["boat_tonnage"].max().rename("largest_tonnage").reset_index() out = units.merge(largest, on=UNIT_KEY, how="left", validate="many_to_one") out["scale_by_boats"] = np.where(out["largest_tonnage"] >= 5, 2, 1) return outWhy each part is there
groupby(UNIT_KEY)uses all four parts. Without the region, region 04's household 5300 would take region 01's boats; without the two key parts, a household's two units would share one largest boat.how="left"keeps the units with no boat; theirlargest_tonnageis missing, which is true: they have no tonnage.validate="many_to_one": the boats' side has one row per unit after themax. The units' side may repeat a key (section 5's duplicates), and each copy gets the samelargest_tonnage.np.where(largest_tonnage >= 5, 2, 1): the code says 5.0 or more, so a boat of exactly 5.0 makes its unit large-scale. A missinglargest_tonnagemakes the comparisonFalse, so a unit with no boat is small-scale, as the codebook has it. Written the other way round,np.where(largest_tonnage < 5, 1, 2), the same missing value would make it large-scale.
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:
- take its table from
frames; keep the rowsapplies_topicks (table.query(applies_to, local_dict=rule_values)), or every row whenapplies_tois empty text or missing; - evaluate
must_holdon them (.eval(must_hold, local_dict=rule_values)); a row fails where the result isFalseor missing; - count the failing rows per household, and add the rule's
rule,table,actionandmessage.
| 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.
The idea
Every rule is the same three steps, scope, condition, count per household, so one loop runs them all; the rules differ only in the data the loop reads.
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 run_rules(spec: pd.DataFrame, frames: dict, values: dict) -> pd.DataFrame: """Run every rule of the specification table on its table: one row per rule and household that fails, REPORT_COLUMNS.""" # Exercise 4.5: the task and examples are in the text above this cell. found = [] for rule in spec.itertuples(index=False): table = frames[rule.table] scope = table.query(rule.applies_to, local_dict=values) if isinstance(rule.applies_to, str) and rule.applies_to.strip() else table holds = scope.eval(rule.must_hold, local_dict=values) failing = scope[~holds.fillna(False).astype(bool)] counts = failing.groupby(HOUSEHOLD).size().rename("rows").reset_index() found.append(counts.assign(rule=rule.rule, table=rule.table, action=rule.action, message=rule.message)) report = pd.concat(found, ignore_index=True)[REPORT_COLUMNS] return report.sort_values(["rule", *HOUSEHOLD]).reset_index(drop=True)Why each part is there
query(applies_to)keeps the rule's scope first, so a skip the questionnaire asks for is never a failure.isinstance(..., str) and .strip()treats an empty scope, or a missing one read from a CSV, as every row.local_dict=valuesis what@educationand@tolerancelook up: the code lists and numbers live outside the expressions, in one place.holds.fillna(False): a condition is missing where a value it needs is blank, and a rule's needed value that is blank fails.~holdsalone would keep<NA>, and the filter would drop the row unseen.groupby(HOUSEHOLD).size()gives one row per household, counting its failing rows: the report's grain. The region is inHOUSEHOLDbecause anhh_idrepeats across regions.- Sorting by rule and household and numbering from 0 makes two runs on the same tables give the same report, row for row, which is what lets module 8 compare a report with the next.
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:
- take its failing rows from the edited tables with
failures, sorted byregion_codeand the row id,row_id; - find the new values: if
drawn_from(rule.edit_to)gives codes, draw one per failing row withrng.choice(codes, size=len(failing)); otherwise evaluatefailing.eval(rule.edit_to, local_dict=values); - write one log row per failing row, then write the new values into the rule's
variableon 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.
The idea
Each rule that carries an edit is the runner's first two steps, then a new value for each failing row, logged before it is written; one seeded generator, used in a fixed order, makes the random edits repeat.
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 apply_edits(spec: pd.DataFrame, frames: dict, values: dict, seed: int) -> tuple[dict, pd.DataFrame]: """Make every edit the specification carries, in its order: the edited tables and the edit log (EDIT_LOG_COLUMNS).""" # Exercise 4.6: the task and examples are in the text above this cell. edited = {name: table.copy() for name, table in frames.items()} log, rng = [], np.random.default_rng(seed) for rule in spec.itertuples(index=False): if not (isinstance(rule.edit_to, str) and rule.edit_to.strip()): continue table = edited[rule.table] failing = failures(table, rule.applies_to, rule.must_hold, values).sort_values(["region_code", ROW_ID]) codes = drawn_from(rule.edit_to) if codes: new, how = rng.choice(codes, size=len(failing)), f"{rule.edit_to}, seed {seed}" else: new, how = failing.eval(rule.edit_to, local_dict=values), rule.edit_to new = pd.Series(new, index=failing.index) for index, row in failing.iterrows(): log.append({"rule": rule.rule, "table": rule.table, "region_code": row["region_code"], "hh_id": int(row["hh_id"]), "row": int(row[ROW_ID]), "variable": rule.variable, "before": as_text(row[rule.variable]), "after": as_text(new[index]), "how": how}) table.loc[failing.index, rule.variable] = new.astype(table[rule.variable].dtype) return edited, pd.DataFrame(log, columns=EDIT_LOG_COLUMNS)Why each part is there
table.copy()for every table: the caller's tables stay as they were, so the edit can be compared with the data it started from, and run again on it.- One
default_rng(seed)for the whole run, made before the loop. A generator made without a seed draws other codes on every run; one made again for each rule would give every random rule the same draws. failures(...)onedited[rule.table], not onframes: each rule sees the table as the rules before it left it, so U7 checks the count of a unit whose blank U4 has just answered with 1.sort_values(["region_code", ROW_ID])before the draw ties each drawn code to a row, not to a position. Rows in another order get the same codes; without the region, region 04's row 1 and region 01's row 1 would sort by arrival.pd.Series(new, index=failing.index)lines the new values up with the failing rows, whetherevalgave one number (2) or a column (boat_rows).- The log row reads
beforefrom the row before Step 5 writes, andhowkeeps the seed beside a draw, so the log alone says how each value came about. .astype(table[rule.variable].dtype): the survey stores a code such asboat_engineas a 32-bit integer, and pandas 3 refuses to write 64-bit values into part of it rather than change the column's type.
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.
The idea
A duplicate is a key that names more than one row; a key with a blank part names nothing, so those rows go first, and every copy of a repeated key stays so the copies can be compared.
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 duplicate_rows(table: pd.DataFrame, key: list) -> pd.DataFrame: """Every row whose key (no part blank) appears more than once in the table, all copies kept, sorted by the key.""" # Exercise 4.7: the task and examples are in the text above this cell. complete = table.dropna(subset=key) return complete[complete.duplicated(subset=key, keep=False)].sort_values(key)Why each part is there
dropna(subset=key)first:duplicatedtreats two blanks as equal, so without it every pair of unregistered boats in a household would be listed under the registration key.keep=Falsemarks every copy. The default,keep="first", marks the second only, and the editor would see one row with nothing to compare it with.sort_values(key)puts the copies of each key together, the way they are read.
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.
The idea
Count the distinct values of each item within each group, and keep the groups where any item has more than one: the definition's "more than one distinct ... within ...", word for word.
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 more_than_one_distinct(table: pd.DataFrame, within: list, counted: list) -> pd.DataFrame: """The groups (by `within`) in which any `counted` column has more than one distinct value, with those numbers.""" # Exercise 4.8: the task and examples are in the text above this cell. counts = table.groupby(within)[counted].nunique().reset_index() return counts[(counts[counted] > 1).any(axis=1)].sort_values(within).reset_index(drop=True)Why each part is there
nunique()counts distinct values, which is what the definitions say.size()orcount()counts rows, and would flag a row stored twice, which has one value repeated; the key test of Exercise 4.7 finds that..any(axis=1)is the definition's "or": one operator's two units share anoperator_lineand differ inunit_no, and.allwould pass them.withinis used as given, the region in it, because anhh_idrepeats across regions: grouped withoutregion_code, region 04's household 5300 would add its boat to region 01's.groupbyleaves out a group whose key has a blank, as an unregistered boat'sboat_reg_noor the area of a household in stratum F;nunique()leaves out a blank among the values counted.