Every exercise in 70_anomalies_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 8.1. Invalid, implausible or unusual: one label per boat
The task
Why it matters: a reviewer acts differently on each kind. An invalid hull is edited by rule or referred; an implausible length is referred to someone who can call the household back; an unusual one is kept. A list of "suspect boats" with no label makes the reviewer work out the kind again, row by row.
Input → output: the boats table (it needs boat_hull and length_m) and the limits table above → a Series with one label per boat, in the boats' order, the first of these that applies:
| label | when |
|---|---|
"invalid" |
the boat's hull is not one of the hulls in limits |
"not measured" |
the length is missing (the size came from the papers) |
"implausible" |
the length is over the hull's plausible_max_m |
"unusual" |
the length is over the hull's typical_max_m |
"ok" |
none of the above |
| boat_hull | length_m | label |
|---|---|---|
| 7 | 30.0 | invalid (not implausible: hull 7 has no limits) |
| 2 | 30.0 | implausible |
| 2 | 13.0 | unusual |
| 1 | 4.0 | ok |
Tools: Series.map() with a Series indexed by hull (module 5), isin, isna, and np.select(conditions, labels, default="ok"), above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
The hull-7 boat of 30 meters is ok |
Its limits are missing, so every comparison is False; the hull was not tested first. | ~boats["boat_hull"].isin(limits["boat_hull"]) first |
The boat with no length is ok |
NaN > limit is False; the missing length was not tested before the limits. |
boats["length_m"].isna() second |
The 30-meter outrigger boat is unusual |
The typical limit was tested before the plausible one. | the order of the conditions |
The hull-7 boat with no length is not measured |
The missing length was tested before the hull. | the hull first |
TypeError: unhashable type or a KeyError in map |
map was given the whole limits table, not one column indexed by hull. |
limits.set_index("boat_hull")["typical_max_m"] |
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 boat gets its hull's two limits beside it, then np.select tries the conditions in order and gives the first label that applies, so a boat that is invalid is never judged on its length.
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 boat_label(boats: pd.DataFrame, limits: pd.DataFrame) -> pd.Series: """One label per boat: invalid, not measured, implausible, unusual or ok, the first that applies.""" # Exercise 8.1: the task and examples are in the text above this cell. by_hull = limits.set_index("boat_hull") typical = boats["boat_hull"].map(by_hull["typical_max_m"]) plausible = boats["boat_hull"].map(by_hull["plausible_max_m"]) conditions = [ ~boats["boat_hull"].isin(limits["boat_hull"]), boats["length_m"].isna(), boats["length_m"] > plausible, boats["length_m"] > typical, ] labels = np.select(conditions, ["invalid", "not measured", "implausible", "unusual"], default="ok") return pd.Series(labels, index=boats.index, name="label")Why each part is there
map(limits.set_index("boat_hull")[...])looks up each boat's limits by its hull. A hull that is not inlimitsgets a missing limit.- The hull is tested first. A comparison with a missing limit is False, so a boat of hull 7 and 30 meters would otherwise fall through every test and come out
"ok". - The missing length is tested before the limits for the same reason:
NaN > 17is False, and a boat sized from its papers would come out"ok", as if it had been measured. - Implausible comes before unusual: a 30-meter outrigger boat is over both limits, and
np.selectkeeps the first condition that is true.
Exercise 8.2. Outside the fences, group by group
The task
Why it matters: this is the first statistical check most survey teams run, on any number in the survey: lengths by hull, household size by stratum, interview minutes by region. Written once for any column and any grouping, it is one line per check.
Input → output: a Series of values, a Series of groups (the same length and index) and k → a Series of True/False, one per value: True where the value is below its group's Q1 − k × IQR or above its group's Q3 + k × IQR. A missing value is never flagged.
| groups | values | k = 1.5 |
|---|---|---|
| A | 1, 2, 3, 4, 5, 6, 7, 8, 9, 30 | only 30 flagged |
| B | 20, 21, 22, 23, 24, 25 | none: ordinary for B, though far above A |
Tools: groupby(groups) on the values, transform with quantile (pandas' default interpolation), comparisons and |, above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| Group B's high values are flagged | The quartiles are the whole column's, not each group's. | values.groupby(groups).transform(...) |
| A table of one row per group, or ValueError: Can only compare identically-labeled Series | .quantile() or .agg() gave one value per group, which does not line up with the values. |
transform, one value per row |
| Too many or too few flags in the k = 3 case | k is not used, or the fence is Q3 + k (no IQR). |
q3 + k * iqr |
| Only high values flagged | The lower fence is missing. | (values < q1 - k * iqr) | (...) |
| TypeError: unsupported operand type(s) for | | A comparison without brackets: | binds before <. |
brackets round each comparison |
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 value gets its own group's quartiles beside it with transform, so the fences are the group's, and the comparison is one line for every group at once.
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 iqr_outliers(values: pd.Series, groups: pd.Series, k: float = 1.5) -> pd.Series: """True where a value is outside its group's fences, Q1 - k*IQR and Q3 + k*IQR.""" # Exercise 8.2: the task and examples are in the text above this cell. by_group = values.groupby(groups) q1 = by_group.transform(lambda v: v.quantile(0.25)) q3 = by_group.transform(lambda v: v.quantile(0.75)) iqr = q3 - q1 return (values < q1 - k * iqr) | (values > q3 + k * iqr)Why each part is there
values.groupby(groups)groups by a Series of labels rather than a column name, so the function works for any pair of columns.transform(lambda v: v.quantile(0.25))returns the group's quartile on every row, lined up withvalues. Quartiles of the whole column would judge a canoe against the decked vessels.k * iqrwidens the fences in proportion to the group's own spread: a group of similar values gets narrow fences, a varied one wide.- A missing value compares False with both fences, so it is never flagged; a check of missing values is a rule's job.
Exercise 8.3. The robust z within groups
The task
Why it matters: a distance, not just a flag, lets a reviewer read the most extreme values first, and the same function serves every numeric item of the survey. Section 3 uses it on ratios.
Input → output: a Series of values and a Series of groups → a Series of robust z, one per value: (x − the group's median) / (1.4826 × the group's MAD). Where a group's MAD is 0, its robust z is missing (NaN), not infinite.
| groups | values | robust z |
|---|---|---|
| A | 1, 2, 3, 4, 100 | median 3, MAD 1: …, 100 → (100 − 3) / 1.4826 = 65.43 |
| B | 5, 5, 5, 5, 9 | MAD 0: all missing |
Tools: groupby(...).transform("median") twice (the second time on the distances), abs(), where, above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
inf or -inf in group B |
The MAD of 0 was not turned into a missing value. | .where(mad > 0) |
| 97.0 instead of 65.43 in group A | The 1.4826 is missing. | 1.4826 * mad |
| Close, but not equal | The mean or the standard deviation instead of the median or the MAD. | transform("median") both times |
| The same MAD for every group | The distances' median was taken over the whole column. | (values - median).abs().groupby(groups) |
| ValueError: cannot reindex on an axis with duplicate labels | groupby(...).median() gave one row per group; it was used as if it lined up with the values. |
transform |
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 median and the median absolute deviation, each put on every row with transform, give a z-score that the outliers it measures cannot pull toward themselves.
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 robust_z(values: pd.Series, groups: pd.Series) -> pd.Series: """(x - group median) / (1.4826 * group MAD), missing where the group's MAD is 0.""" # Exercise 8.3: the task and examples are in the text above this cell. median = values.groupby(groups).transform("median") mad = (values - median).abs().groupby(groups).transform("median") return ((values - median) / (1.4826 * mad)).where(mad > 0)Why each part is there
transform("median")puts the group's median on every row; the mean would move toward the outliers.- The MAD is the median of the distances from the median, computed within the group:
(values - median).abs()grouped again. Distances from the mean, or one MAD for all groups, give other numbers. 1.4826makes the MAD estimate the standard deviation for normal data, so 3.5 means what a z-score's 3.5 means. R'smad()has it built in; scipy'smedian_abs_deviationdoes not by default..where(mad > 0)turns the divisions by zero into missing values. Infinity would sort to the top of every list and flag every value that is not the median.
Exercise 8.4. HB's effects: centered ratios weighted by size
The task
Why it matters: the centering and the size term are what make HB more than an outlier check on a ratio. Get them right and Exercise 8.5's fences do the rest.
Input → output: two Series x and y (positive numbers, the same index), a Series of groups and the exponent U → a Series of effects e, one per unit, as the table above defines them:
| group | x | y | ratio | group's median ratio | s | U = 0.5: e = s × max(x, y)^0.5 |
|---|---|---|---|---|---|---|
| A | 5 | 10 | 0.5 | 1 | 1 − 1 / 0.5 = −1 | −1 × √10 = −3.162 |
| A | 20 | 10 | 2 | 1 | 2 / 1 − 1 = 1 | 1 × √20 = 4.472 |
| B | 40 | 4 | 10 | 1 | 10 / 1 − 1 = 9 | 9 × √40 = 56.921 |
Tools: transform("median") within groups, where (or np.where) for the two cases of s, np.maximum(x, y) and **.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| −0.5 where the ratio is half the median (exponent 0) | ratio / median - 1 on both sides. |
1 - median / ratio below the median |
| 0.5 where the ratio is half the median | The two cases are swapped. | where(ratio < median, ...): the first argument is kept where the condition is True |
| Effects match with exponent 0 but not 0.5 | The size is x or y, not the larger of the two. |
np.maximum(x, y) ** exponent |
| Every ratio centered on 1, or on the whole column's median | The median is not the group's. | ratio.groupby(groups).transform("median") |
| ValueError: The truth value of a Series is ambiguous | if ratio < median: on a whole column. |
where or np.where |
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 centering makes a ratio half its group's median and one double it equally far from 0; the size term then gives a deviation in a large unit more weight than the same deviation in a small one.
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 hb_effects(x: pd.Series, y: pd.Series, groups: pd.Series, exponent: float) -> pd.Series: """Hidiroglou-Berthelot's effects: each ratio x/y centered on its group's median ratio, times max(x, y)**exponent.""" # Exercise 8.4: the task and examples are in the text above this cell. ratio = x / y median = ratio.groupby(groups).transform("median") centered = (1 - median / ratio).where(ratio < median, ratio / median - 1) return centered * np.maximum(x, y) ** exponentWhy each part is there
ratio.groupby(groups).transform("median")puts the group's median ratio beside each ratio, so each province is centered on its own adjustment.- Below the median,
1 - median / ratiogives −1 for half the median; above it,ratio / median - 1gives +1 for double. One formula on both sides (ratio / median - 1) gives −0.5 for half, and the low side's errors look half as large. np.maximum(x, y)is the larger of the unit's two values, its size in either state: a weight cut to a tenth by mistake is still a large unit, andxalone would hide it.** exponent: 0 makes the size factor 1, so only the centered ratio counts; 1 multiplies by the full size.
Exercise 8.5. HB's fences: quartile distances with a minimum
The task
Why it matters: the fences decide which effects a reviewer sees. Each side takes its own distance from the median, so a group whose effects spread more on one side is not judged as if it were symmetric; the minimum keeps a group of nearly identical effects from flagging every small difference.
Input → output: a Series of effects, a Series of groups, the multiplier c and the minimum distance multiplier a → a Series of True/False: True where the effect is below E_M − c × d_Q1 or above E_M + c × d_Q3, with d_Q1 = max(E_M − E_Q1, |a × E_M|) and d_Q3 = max(E_Q3 − E_M, |a × E_M|), all within the group.
| group | effects | E_Q1 = E_M = E_Q3 | d with a = 0.05 | c = 4: fences | flagged |
|---|---|---|---|---|---|
| A | 10 seven times, 10.4, 13 | 10 | 0.5 | 8 and 12 | only 13 (with no minimum, 10.4 too) |
The function works on any numbers, not only HB's effects, so the check also gives it other columns.
Tools: transform with quantile and "median", np.maximum, abs(), comparisons, above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| 10.4 flagged in group A | The minimum distance is missing: A's quartiles equal its median, so its fences have no width. | np.maximum(median - q1, (a * median).abs()) |
| Group C flags -10.4 | a * median is negative there and was used without abs(), so the minimum is lost. |
(a * median).abs() |
| Group B's flags differ from the check | One distance (the IQR) used on both sides. | median - q1 below, q3 - median above |
| Fences around the whole column, not each group | The quartiles were not computed within groups. | effects.groupby(groups).transform(...) |
| TypeError: '>' not supported or ValueError: ambiguous | Python's max() on two Series. |
np.maximum works element by element |
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
Fences built from each side's own quartile distance to the median, never narrower than a small share of the median, so a lopsided group is judged on each side by its own spread.
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 hb_outliers(effects: pd.Series, groups: pd.Series, c: float, a: float = 0.05) -> pd.Series: """True where an effect is outside its group's HB fences, E_M - c*d_Q1 and E_M + c*d_Q3.""" # Exercise 8.5: the task and examples are in the text above this cell. by_group = effects.groupby(groups) q1 = by_group.transform(lambda e: e.quantile(0.25)) median = by_group.transform("median") q3 = by_group.transform(lambda e: e.quantile(0.75)) low = median - c * np.maximum(median - q1, (a * median).abs()) high = median + c * np.maximum(q3 - median, (a * median).abs()) return (effects < low) | (effects > high)Why each part is there
transformputs the group's quartiles and median on every row, lined up with the effects.np.maximum(median - q1, (a * median).abs()): when the lower quartile equals the median, the distance would be 0, and any effect a hair below the median would be flagged. The minimum gives the fence some width.- Two distances, not one IQR: an effect far below the median is judged by how far the lower quarter of the group spreads, an effect far above by the upper quarter.
abs()ona * median: a group whose median effect is negative would otherwise get a negative minimum, whichmaximumwould ignore.
Exercise 8.6. A ratio out of line with its group
The task
Why it matters: a ratio check catches errors that keep each item plausible alone: a dimension in the wrong unit, a tonnage computed wrong, a count copied into the wrong column. One function serves every pair of items.
Input → output: a Series numerator, a Series denominator, a Series of groups and a cutoff → a Series of True/False: True where the robust z of log(numerator / denominator) within the group is beyond the cutoff on either side. Where a group's MAD is 0, or the ratio is missing, nothing is flagged.
| group | ratios | cutoff 3.5 |
|---|---|---|
| A | 1.0, 1.1, 0.9, 1.05, 0.95, 10, 0.1 | 10 and 0.1 both flagged |
| B | 2, 2, 2, 3 | MAD 0: nothing flagged |
Tools: np.log, the robust z of Exercise 8.3 (write it again here, or call your robust_z), abs(), fillna or a comparison that is False on missing values.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| The ratio of 10 flagged, the ratio of 0.1 not | The robust z of the ratio, not of its log. | np.log(numerator / denominator) |
| Group B's ratios flagged | The MAD of 0 gave infinity. | .where(mad > 0) |
| The pair with no denominator flagged | A missing z compared as True, or filled with a large number. | z.abs() > cutoff is False on a missing value |
| Only one side flagged | z > cutoff without abs(). |
z.abs() |
| RuntimeWarning: divide by zero encountered in log | A numerator of 0: its log is minus infinity. Check the data; the survey's boats have no tonnage of 0. | the ratio's numerator |
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
On the log scale a ratio ten times the usual and one a tenth of it are equally far from the center, so the robust z of the log ratio flags both, each within its own group.
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 ratio_outliers(numerator: pd.Series, denominator: pd.Series, groups: pd.Series, cutoff: float = 3.5) -> pd.Series: """True where the robust z of log(numerator / denominator) within its group is beyond the cutoff on either side.""" # Exercise 8.6: the task and examples are in the text above this cell. log_ratio = np.log(numerator / denominator) median = log_ratio.groupby(groups).transform("median") mad = (log_ratio - median).abs().groupby(groups).transform("median") z = ((log_ratio - median) / (1.4826 * mad)).where(mad > 0) return z.abs() > cutoffWhy each part is there
np.log(numerator / denominator): without the log, ratios pile up just above 0 and stretch far above the median, so ten times the usual ratio lands much farther out than a tenth of it, though the two are as unusual. On the log scale they sit at the same distance.- The median and the MAD are the group's, as in Exercise 8.3, so the tonnage per meter of a canoe is judged against canoes.
.where(mad > 0): a group where more than half the ratios are equal has no spread to measure. Infinity would flag every ratio that differs from the median.z.abs() > cutoffis False wherezis missing, so a boat with no length is not flagged here; that is the job of Exercise 8.1's labels.
Exercise 8.7. How much a weight dominates its domain
The task
Why it matters: an estimate for a small domain can rest on a few households with large weights. Before an estimate is published, the estimation team needs to know which households carry it, and whether they belong in it.
Input → output: a Series of weights and a Series of domains → a table with one row per household, in the same order, and two columns: vs_median (the weight over its domain's median weight) and share (the weight over its domain's total weight).
| domain | weight | vs_median | share |
|---|---|---|---|
| A | 1 | 1.0 | 0.0435 |
| A | 1 | 1.0 | 0.0435 |
| A | 1 | 1.0 | 0.0435 |
| A | 20 | 20.0 | 0.8696 |
The median, not the mean: A's mean weight is 5.75, which the heavy household itself pulled up.
Tools: groupby(domains).transform("median") and transform("sum"), pd.DataFrame({...}), above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| 3.48 for the heavy household, not 20 | The mean, not the median. | transform("median") |
share adds up to 1 over all rows, not per domain |
The total of all weights. | transform("sum") within domains |
| One row per domain | .median() or .agg() instead of transform. |
transform |
| KeyError: 'vs_median' | The columns are named otherwise. | vs_median and share |
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
Two numbers on every row, each the weight over a figure of its own domain: the median says how many typical households it counts as, the total what share of the domain's count rests on it.
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 weight_influence(weights: pd.Series, domains: pd.Series) -> pd.DataFrame: """Each weight over its domain's median weight (vs_median) and over its domain's total weight (share).""" # Exercise 8.7: the task and examples are in the text above this cell. by_domain = weights.groupby(domains) return pd.DataFrame({"vs_median": weights / by_domain.transform("median"), "share": weights / by_domain.transform("sum")})Why each part is there
transform("median")andtransform("sum")put the domain's figures on every row, so the divisions line up with the weights.- The median, not the mean: the households the check looks for pull the mean toward themselves, and in a small domain a few of them make every weight look ordinary.
- Both are kept in the domain's own terms: a weight of 15 is ordinary among small-scale households and dominant among large-scale ones.
Exercise 8.8. Whipple's index
The task
Why it matters: age heaping is the rounding indicator that needs nothing but the roster, and the survey has ages for every member. Computed per interviewer, it shows whose ages are guessed.
Input → output: a Series of ages → one number, Whipple's index on the ages from 23 to 62, both included. Ages outside that range, and missing ages, do not count.
| ages | Whipple |
|---|---|
| 23, 24, …, 62 (each once) | 100.0 |
| 25, 30, 35, 40 | 500.0 |
| 20, 23, 25, 63, 65, 70 | 23 and 25 count: 100 × 1 / (2 / 5) = 250.0 |
Tools: boolean masks with between or >= and <=, % 5, .sum(), len().
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| 0.2 for the ages 23 to 62 | Divided by all the ages kept, not a fifth of them, and not times 100. | 100 * count / (len(kept) / 5) |
| 97.56 for the ages 23 to 62 | One end of the range left out (> 23 or < 62), so 40 years became 39. |
>= 23 and <= 62 |
| 333.33 for the third case | Ages outside 23 to 62 counted. | the range mask first |
| TypeError: unsupported operand type(s) for & | A comparison without brackets. | (ages >= 23) & (ages <= 62) |
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
Among ages 23 to 62 exactly a fifth end in 0 or 5, so the count that do, over a fifth of all of them, is 1 without heaping; times 100, the index reads 100 for none and 500 for all.
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 whipple(ages: pd.Series) -> float: """Whipple's index of age heaping: 100 * (ages 23-62 ending in 0 or 5) / (ages 23-62 / 5).""" # Exercise 8.8: the task and examples are in the text above this cell. kept = ages[(ages >= 23) & (ages <= 62)] return 100 * (kept % 5 == 0).sum() / (len(kept) / 5)Why each part is there
(ages >= 23) & (ages <= 62)keeps 40 whole years, eight of each last digit pattern, so 0 and 5 are exactly a fifth of the years. Children's ages, which parents know, and old ages, which are rare, stay out.% 5 == 0is True for ages ending in 0 or 5.len(kept) / 5is the count expected without heaping; dividing by it, not bylen(kept), makes the index 100 rather than 0.2 for no heaping.
Exercise 8.9. Pace and repeated answers, interviewer by interviewer
The task
Why it matters: the time indicators were the strongest in the comparison above, and the repeated answers are what a falsifier saves time with. Together they are the table a field supervisor reads each week.
Input → output: the households table (it needs region_code, hh_id, hh_interviewer, hh_interview_date and hh_interview_minutes) and the catch table (it needs region_code, hh_id and catch_species) → one row per hh_interviewer with:
interviews: how many households the interviewer interviewed;busiest_day: the most interviews the interviewer held on one date;median_minutes: the median of their interviews' minutes;repeated_catch: the share of their interviews whose catch list is the same as the catch list of at least one other interview by the same interviewer. A household's catch list is its species codes, each once, sorted, as text:"103,104,304". An interview with no catch row has no list, and counts as not repeated.
| hh_interviewer | interviews | busiest_day | median_minutes | repeated_catch |
|---|---|---|---|---|
| I1 | 4 | 3 | … | 1.0 |
| I2 | 2 | 1 | … | 0.0 (its one list is also I1's, but no other of I2's) |
A household is a region and an id: join the catch to the households on both, or a household of region 07 takes the catch of the household with the same id in region 01.
Tools: groupby with two keys and .size(), a grouped max, agg with a function that builds the list (lambda s: ",".join(...)), merge on CASE, transform("size").
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
I1's repeated_catch is below 1.0 |
The lists were built from the rows in their order, or with the duplicated row twice: "304,103" is not "103,304", and "103,103" is not "103". |
sorted(set(s)) |
I2's repeated_catch is above 0 |
Lists were counted across interviewers. | groupby(["hh_interviewer", "catch_list"]) |
| I2 has 1 interview, or its share is out of 1 | The household with no catch was dropped by an inner join. | merge(..., how="left") |
| I2's household 1 has I1's catch, or more rows than interviews | The catch was joined on hh_id alone. |
on=CASE |
busiest_day equals interviews |
Counted per interviewer, not per interviewer and date. | groupby(["hh_interviewer", "hh_interview_date"]).size() |
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
Pace from counting interviews per interviewer and date; sameness from each household's catch list as one text, counted within the interviewer's own interviews.
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 interviewer_indicators(households: pd.DataFrame, catch: pd.DataFrame) -> pd.DataFrame: """One row per interviewer: interviews, busiest_day, median_minutes and repeated_catch.""" # Exercise 8.9: the task and examples are in the text above this cell. per_interviewer = households.groupby("hh_interviewer").agg(interviews=("hh_id", "size"), median_minutes=("hh_interview_minutes", "median")) per_day = households.groupby(["hh_interviewer", "hh_interview_date"]).size() per_interviewer["busiest_day"] = per_day.groupby("hh_interviewer").max() lists = catch.groupby(CASE)["catch_species"].agg(lambda s: ",".join(str(code) for code in sorted(set(s)))).rename("catch_list").reset_index() interviews = households[[*CASE, "hh_interviewer"]].merge(lists, on=CASE, how="left", validate="one_to_one") interviews["repeated"] = interviews.groupby(["hh_interviewer", "catch_list"])["catch_list"].transform("size").gt(1) per_interviewer["repeated_catch"] = interviews.groupby("hh_interviewer")["repeated"].mean() return per_interviewerWhy each part is there
groupby(["hh_interviewer", "hh_interview_date"]).size()counts each interviewer's interviews per date; the largest of those counts is the busiest day. A count per date across all interviewers would mix their work.",".join(str(code) for code in sorted(set(s)))makes one text per household, the same whatever order the rows came in and however often a species was entered, so two households with the same species have equal lists.- The merge is on both
region_codeandhh_id, andhow="left"keeps the interviews with no catch: they count in the denominator as not repeated. transform("size")within interviewer and list counts how many of the interviewer's own interviews share it; grouping by the list alone would count another interviewer's identical, honest list.
Exercise 8.10. One row per household, ranked
The task
Why it matters: this is the table the reviewer works through, top to bottom, and the order is where the reviewer's day goes.
Input → output: a long flags table (region_code, hh_id, source, flag; a household can have the same flag twice, from two boats) and a weights table (region_code, hh_id, sel_final_weight, one row per household) → one row per flagged household with:
| column | what it holds |
|---|---|
region_code, hh_id |
the household |
sources |
the number of different sources |
flags |
the number of different flags |
reasons |
the different flags, sorted, joined with "; " |
sel_final_weight |
the household's final weight |
rank |
1, 2, 3, … in the table's order |
sorted by sources, then flags, then sel_final_weight, each largest first, then region_code and hh_id, each smallest first:
| region_code | hh_id | sources | flags | reasons | sel_final_weight | rank |
|---|---|---|---|---|---|---|
| 01 | 1 | 2 | 2 | M1 sex; weight high | 20.0 | 1 |
| 04 | 7 | 1 | 2 | crowded day; short interview | 1.0 | 2 |
| 04 | 2 | 1 | 1 | M1 sex | 50.0 | 3 |
| 07 | 1 | 1 | 1 | C1 species | 50.0 | 4 |
| 01 | 2 | 1 | 1 | weight high | 21.0 | 5 |
Household 01-1 has M1 sex from two members: it counts once. Households 04-2 and 07-1 tie on everything but the region. Household 07-2 has a weight and no flag, so it has no row.
Tools: groupby(CASE).agg() with "nunique" and a lambda that joins, merge, sort_values(by=[...], ascending=[...]), above.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
Household 01-1 has flags 3 and M1 sex; M1 sex; weight high |
The same flag counted twice. | "nunique", and sorted(set(f)) |
| 04-2 and 07-1 in the other order | The tie on sources, flags and weight is broken by row order. | region_code and hh_id as the last keys, smallest first |
| The smallest weights first | One ascending=False for every key, or True for all. |
ascending=[False, False, False, True, True] |
rank not 1, 2, 3 in order |
The rank was set before sorting, or from the old index. | reset_index(drop=True) after sorting |
| The household with no flag has a row | The weights table was the left side of the join. | start from the flags |
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
Collapse the long table to one row per household, count what differs (sources and flags), keep the reasons as one text, then sort on the three keys and number the rows.
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 review_table(flags: pd.DataFrame, weights: pd.DataFrame) -> pd.DataFrame: """One row per flagged household: sources, flags, reasons, sel_final_weight and rank, the likeliest errors first.""" # Exercise 8.10: the task and examples are in the text above this cell. table = flags.groupby(CASE).agg( sources=("source", "nunique"), flags=("flag", "nunique"), reasons=("flag", lambda f: "; ".join(sorted(set(f)))), ).reset_index() table = table.merge(weights[[*CASE, "sel_final_weight"]], on=CASE, how="left", validate="one_to_one") table = table.sort_values(["sources", "flags", "sel_final_weight", "region_code", "hh_id"], ascending=[False, False, False, True, True]).reset_index(drop=True) table["rank"] = range(1, len(table) + 1) return tableWhy each part is there
"nunique", not"size": a household with two long boats has the same flag twice, and counting it twice would rank it above a household two different checks agree on."; ".join(sorted(set(f)))gives each different flag once, in the same order every time, so two runs give the same text.ascending=[False, False, False, True, True]: one value per key. The last two keys break ties in a fixed order; without them, equal households come out in whatever order the flags arrived.reset_index(drop=True)before the rank, so the rank follows the sorted order and not the old row numbers.
Exercise 8.11. Recall by kind, for the rows a reviewer reads
The task
Why it matters: "the table finds 90% of the errors" hides which errors. Recall by kind shows what the checks miss and how deep each kind sits, which tells a survey team where a new check would help and how many rows a reviewer must read.
Input → output: a review table (one row per household, in reading order; it needs region_code and hh_id), the planted defects (region_code, hh_id, kind) and read, how many rows from the top are read → one row per kind of the defects, with:
planted: the households of that kind (each household once per kind);found: how many of them are in the firstreadrows of the review;recall: found / planted.
Every kind of the defects has a row, including those with nothing found (found 0, recall 0).
| kind | planted | found (read = 2) | recall |
|---|---|---|---|
| final_weight_inflated | 2 | 1 | 0.5 |
| code_not_in_list | 1 | 0 | 0.0 |
Tools: head(read), merge(..., how="left", indicator=True) or a marker column, drop_duplicates, groupby("kind").agg().
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
No row for code_not_in_list |
The kinds came from the review, or an inner join dropped the kind nothing found. | the defects on the left, how="left" |
final_weight_inflated planted 3, not 2 |
Household 01-1, listed twice for one kind, was counted twice. | drop_duplicates() on the defects' household and kind |
found equals planted in every row |
"size" counts every row, marked or not. |
("found", "count") |
| The read = 2 case finds as much as read = 4 | The whole review was used, not its first rows. | review.head(read) |
| MergeError or a household counted twice | The households read were not made unique before the join. | drop_duplicates() on the households 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
Mark the households read, join the marks onto the planted defects so every planted household keeps its row, and count per kind how many are marked.
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 recall_by_kind(review: pd.DataFrame, defects: pd.DataFrame, read: int) -> pd.DataFrame: """One row per kind of the defects: planted, found in the first `read` rows of the review, and recall.""" # Exercise 8.11: the task and examples are in the text above this cell. seen = review.head(read)[CASE].drop_duplicates().assign(found=True) planted = defects[[*CASE, "kind"]].drop_duplicates().merge(seen, on=CASE, how="left") out = planted.groupby("kind").agg(planted=("kind", "size"), found=("found", "count")) out["recall"] = out["found"] / out["planted"] return outWhy each part is there
review.head(read): the table is already in reading order, so the first rows are what a reviewer who stops there has seen.drop_duplicates([*CASE, "kind"]): the list can name one household twice for one kind (two boats, say); recall counts households.- The defects on the left with
how="left"keep the kinds nothing found, which an inner join, or grouping the review, would drop: the kinds a check misses are what the table is for. ("found", "count")counts the rows where the marker is present;"size"would count every planted household as found.