Skip to content
Learn Python with BNHR

Module 8: Anomalies by rule and by statistics

On this page
  1. Overview
  2. 8.1 · Invalid, implausible or unusual: one label per boat
  3. 8.2 · Outside the fences, group by group
  4. 8.3 · The robust z within groups
  5. 8.4 · HB's effects: centered ratios weighted by size
  6. 8.5 · HB's fences: quartile distances with a minimum
  7. 8.6 · A ratio out of line with its group
  8. 8.7 · How much a weight dominates its domain
  9. 8.8 · Whipple's index
  10. 8.9 · Pace and repeated answers, interviewer by interviewer
  11. 8.10 · One row per household, ranked
  12. 8.11 · Recall by kind, for the rows a reviewer reads

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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 first read rows 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.

Something new

Identify results
LayerExplore a stretch exercises
Stretch exercises S3Stretch: detection
AboutStretch exercises S3 of Python for Survey Statistics, after module 9: more anomaly detection, for those who finish early or want more.
CoursePython for Survey Statistics, free