Every exercise in 61_stretch_tabulation.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.
Stretch S2.1. Fishing units by species label, in polars
The task
Why it matters: fishing units by the top eight species is a table every round of the survey publishes. Its "Other" row and its total are where a row count goes wrong, and the error is invisible in the table: every number looks plausible.
Input → output: a polars table of catch rows with the unit's key (UNIT_KEY: region_code, hh_id, operator_line, unit_no) and a species_label column → a polars table with one row per label and a last row "Total":
| species_label | units |
|---|---|
| Other | units that caught at least one species labeled Other |
| Squids | … |
| Total | units that caught anything |
Tools: group_by(...).agg(pl.struct(UNIT_KEY).n_unique()), select(...).item(), pl.concat with how="vertical_relaxed" (which lets the total's whole number join the counts' column), from module 5, section 2. The row order does not matter.
If the check is red
Count distinct units (pl.struct of UNIT_KEY, n_unique) per label, and once more over the whole table for Total.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Count units, not catch rows, in every row of the table, the total included: pl.struct bundles the unit's four key columns into one value, and n_unique counts the distinct bundles.
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 units_by_label(catch: pl.DataFrame) -> pl.DataFrame: """Distinct fishing units per species_label, and a last row Total: the distinct units in the whole table.""" # Exercise S2.1: the task and examples are in the text above this cell. by_label = catch.group_by("species_label").agg(pl.struct(UNIT_KEY).n_unique().alias("units")) total = pl.DataFrame({"species_label": ["Total"], "units": [catch.select(pl.struct(UNIT_KEY).n_unique()).item()]}) return pl.concat([by_label, total], how="vertical_relaxed")Why each part is there
pl.struct(UNIT_KEY).n_unique()counts units once per label: a unit with two species pooled into "Other", or a catch row entered twice, counts once.pl.len()would count catch rows.- The whole key, region included: two regions can share a household id, so a key without
region_codemerges their units. - The total is counted again over the whole table, not summed from the rows: a unit caught several species, so it is in several rows, and the sum counts it once per row.
how="vertical_relaxed"lets the two tables stack although their count columns have different integer types (n_uniquegives an unsigned 32-bit count, the literal total a 64-bit one).
Stretch S2.2. The design effect of a total, from the formula
The task
Why it matters: a deff is how a survey's precision is compared across items and rounds, and how the next round's sample size is planned. Computing it yourself shows what it compares with what.
If the check is red
V_design = taylor_variance(frame, w*y); V_SRS = N² (1 − n/N) s²/n with the weighted s², n/(n−1) included.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
The design's variance of the total over the variance a simple random sample of the same n would give, both estimated from the same 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 design_effect(frame: pd.DataFrame, y: str) -> float: """The design effect of the total of y: the design's variance over a simple random sample's without replacement.""" # Exercise S2.2: the task and examples are in the text above this cell. w = frame["sel_final_weight"] values = frame[y].astype(float) positive = w > 0 n = int(positive.sum()) N = w[positive].sum() mean = (w * values)[positive].sum() / N s2 = n / (n - 1) * (w * (values - mean) ** 2)[positive].sum() / N v_srs = N**2 * (1 - n / N) * s2 / n return taylor_variance(frame, w * values) / v_srsWhy each part is there
s²is the weighted variance: it estimates the population's variance of y, which an unweighted variance of the sample would not (the households of stratum F, taken in full, would count as much as a household that stands for twenty).N² · s² / nis the variance of N times a sample mean;(1 − n/N)is the simple random sample's own fpc, whichdeff="wor"includes and"wr"leaves out.- Only rows with a positive weight count in n: a row of weight 0 is in the table but stands for no household.
Stretch S2.3. Publish, caution or suppress
The task
Why it matters: the rule is applied to every cell of every table, by a script, and printed in the table's notes. It must handle the CV a library gives (a fraction), the estimates whose CV can't be computed (an estimate of 0 gives an infinite CV), and the values that fall exactly on a threshold.
Input → output: a table with a column cv (a fraction, as svy gives it), and two thresholds as fractions, caution=0.20 and suppress=0.35 → a Series of labels, one per row, in the table's order:
| cv | label |
|---|---|
| 0.05 | publish |
| 0.20 | publish (at the threshold: publish) |
| 0.25 | caution |
| 0.35 | caution |
| 0.36 | suppress |
| missing, or infinite | suppress |
Tools: np.isfinite, comparisons, and np.select (module 5).
If the check is red
cv is a fraction; suppress when it is missing, infinite or above suppress; caution when above caution; publish otherwise.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Three labels from two thresholds, the worst checked first, and a CV that can't be computed treated as the worst.
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 reliability(table: pd.DataFrame, caution: float = 0.20, suppress: float = 0.35) -> pd.Series: """A label for each row's CV: publish (cv <= caution), caution (cv <= suppress), or suppress (above, or no CV).""" # Exercise S2.3: the task and examples are in the text above this cell. cv = table["cv"].astype(float).to_numpy() labels = np.select([~np.isfinite(cv) | (cv > suppress), cv > caution], ["suppress", "caution"], default="publish") return pd.Series(labels, index=table.index, name="reliability")Why each part is there
~np.isfinite(cv)catches both a missing CV and an infinite one: svy givesinffor an estimate of 0, and a comparison withinf > 0.35would say suppress butnan > 0.35says False and would publish it.np.selecttakes the first condition that holds, sosuppressis checked beforecaution; the other order would label a CV of 0.40 caution.>rather than>=: a CV at the threshold is inside it, as the task's table says. A rule that reads "below 20%" changes one sign.
Stretch S2.4. Margins from their own estimates
The task
Why it matters: a cross table has a "Total" row and column: all provinces, all sexes. A total adds up: the operators of all provinces are the sum of each province's. Its standard error does not. The cells share sampling units (a drawn area holds men and women), so their errors move together, and the margin's SE is neither the sum of the cells' SEs nor the square root of the sum of their variances. It comes from estimating the margin itself, on the full design. The cell below shows it on the nine operators of the check: province P's two cells, and the margin svy estimates for P.
If the check is red
Every subset of the variables (itertools.combinations, sizes 0 to all), each estimated on the full sample, 'Total' in the variables it leaves out; then lay them on the grid of each variable's levels plus 'Total'.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A margin is a domain of its own: estimate it from the full design, as a cell is, and put "Total" where the variables it adds over would go. Then one grid, with "Total" added to every variable's categories, orders the cells and margins together.
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 with_margins(sample: svy.Sample, y: str, levels: dict) -> pd.DataFrame: """The cells of labeled_cells and every margin ("Total" in each variable a margin adds over), each estimated on the full design, in product order with "Total" last in each variable.""" # Exercise S2.4: the task and examples are in the text above this cell. names = list(levels) parts = [] for k in range(len(names) + 1): for kept in itertools.combinations(names, k): if kept: part = labeled_cells(sample, y, {name: levels[name] for name in kept}) else: whole = sample.estimation.total(y=y).to_polars().to_pandas() part = whole[["est", "se", "cv", "n"]].assign(reliability=reliability_label(whole["cv"])) parts.append(part.assign(**{name: TOTAL for name in names if name not in kept})) grid = pd.DataFrame(itertools.product(*([*levels[name], TOTAL] for name in names)), columns=names) table = grid.merge(pd.concat(parts, ignore_index=True), on=names, how="left", validate="one_to_one") return table[[*names, "est", "se", "cv", "n", "reliability"]]Why each part is there
itertools.combinations(names, k)for k from 0 to the number of variables lists every margin once: for two variables, the grand total (k = 0), the two one-way margins and the cells. For three, eight tables.- Each margin gets its SE from its own estimate. Adding the cells' SEs, or their variances, ignores how the cells move together through shared sampling units; the cell above showed both missing svy's figure.
- The grand total has no domain, so it is
estimation.total(y=y)with noby=, labeled byreliability_labelas every other row. Itsnis every sampled row. - The grid with
"Total"added at the end of each variable's list puts every margin after its categories, the way a cross table prints them, and keepslabeled_cells' empty cells.
Stretch S2.5. A proportion and its confidence interval
The task
Why it matters: "what share of the operators of large-scale units are women, by province?" is a proportion in a small domain: a province's sampled operators of large-scale units, and the few women among them. svy's estimation.prop gives each share with its SE and a 95% confidence interval. Which interval matters here. The textbook interval, estimate plus and minus t standard errors (the Wald interval), is symmetric, so for a small share with a large SE it runs below 0%: a range of possible shares that includes impossible ones. svy's default, the logit interval, is computed on the log-odds scale and turned back, so it stays between 0 and 1 and is lopsided where the share is near either end (module 6, section 2):
t = Student's t at (1 + level) / 2, with the domain's degrees of freedom
Wald = p ± t · SE
logit = expit( logit(p) ± t · SE / (p · (1 − p)) ), logit(p) = log(p / (1 − p)), expit(x) = 1 / (1 + e^(−x))
svy's prop returns two rows per domain, one for each value of the 0/1 column: the share of men (female = 0) and the share of women (female = 1). Their shares add to 1 and their SEs are equal.
If the check is red
Keep the rows where y is 1; t = stats.t.ppf(1 - (1 - level) / 2, df); Wald is est ± t·se; logit is expit(logit(est) ± t·se / (est·(1 − est))).
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Both intervals are the estimate plus and minus t standard errors, on two scales: the share's own, where nothing stops the interval at 0, and the log-odds, which maps back into 0 to 1 whatever the width.
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 proportion_intervals(table: pd.DataFrame, y: str, level: float = 0.95) -> pd.DataFrame: """The rows of a svy prop result where y is 1, with the Wald and the logit confidence intervals at this level.""" # Exercise S2.5: the task and examples are in the text above this cell. rows = table[table[y] == 1].drop(columns=y) t = stats.t.ppf(1 - (1 - level) / 2, rows["df"]) half = t * rows["se"] / (rows["est"] * (1 - rows["est"])) out = rows.assign( wald_lci=rows["est"] - t * rows["se"], wald_uci=rows["est"] + t * rows["se"], logit_lci=special.expit(special.logit(rows["est"]) - half), logit_uci=special.expit(special.logit(rows["est"]) + half), ) domains = [c for c in rows.columns if c not in ("est", "se", "lci", "uci", "cv", "df", "n")] return out[[*domains, "est", "se", "df", "wald_lci", "wald_uci", "logit_lci", "logit_uci"]].reset_index(drop=True)Why each part is there
- svy's
propgives a row for each value ofy; the share asked for is the row whereyis 1. The row where it is 0 is its complement, with the same SE, so a table that keeps both prints every domain twice. - t comes from each row's own degrees of freedom, the domain's sampling units less its strata: with 15 of them t is 2.13, not 1.96, and a small domain has few. With 0 degrees of freedom,
stats.t.ppfgives NaN, and both intervals with it. - The logit's SE is the share's SE divided by p(1 − p), the derivative of the log-odds (the delta method). That is why a share near 0 or 1, with a small p(1 − p), gets a wide interval on the log-odds scale that turns back into a lopsided one.
special.expitandspecial.logitare the two transforms, each the other's inverse. An SE of 0 gives a half-width of 0 on either scale, so both intervals collapse to the estimate.
Stretch S2.6. The cross table as a reader sees it
The task
Why it matters: module 7 wrote long tables, one estimate per row (and S2.7 below adds a flag column). A cross table puts one variable down the side and one across the top, so a reader compares a province's women and men in one line. With the flags gone as a column, each cell has to carry its own label, and statistical tables use symbols for it. This workbook uses three, explained in its notes sheet:
| the cell's reliability | what the cell shows | what the cell holds |
|---|---|---|
| publish | 3,379 |
the estimate, a number, formatted #,##0 |
| caution | 821* |
the estimate, a number, formatted #,##0"*": the asterisk is part of the format, so the cell still adds up in a formula |
| suppress | .. |
the text ..: no estimate is published |
| no sample | - |
the text -: nobody in the sample, so nothing to estimate |
A number format can carry text in quotes: Excel shows #,##0"*" as the number with an asterisk after it, and the cell keeps the number. Writing the text "821*" instead would make the cell text, which a reader's SUM skips.
Input → output: a workbook, a sheet title, a long table of cells (labeled_cells' or S2.4's columns, with est and reliability), the names of the variables down the side (rows, a list of one or more) and the name of the variable across the top (column) → the new sheet, added at the end of the workbook, holding:
- row 1: the names in
rows, then each category ofcolumnin the order it first appears in the table, all bold; - one row per combination of the
rowsvariables, in the order it first appears in the table: the combination's values, then one cell per category ofcolumn, as the table above says; - a combination the table does not hold shows
-, as a cell with no sample does; - the panes frozen at the first cell of numbers:
B2with one variable down the side,C2with two.
The first rows of the check's small made-up table, as the sheet shows them:
| A | B | C | D | |
|---|---|---|---|---|
| 1 | province | scale | Male | Female |
| 2 | La Union | Large-scale | 60* |
.. |
| 3 | La Union | Small-scale | 3,379 |
821* |
Tools: workbook.create_sheet, sheet.append, sheet.cell(row=..., column=..., value=...), cell.number_format, Font(bold=True), sheet.freeze_panes (module 7, Exercise 7.2); pd.unique keeps the order of first appearance; drop_duplicates on the rows columns does the same for combinations; get_column_letter(n) turns 3 into "C".
If the check is red
create_sheet; a bold header of the rows' names and the column's categories (pd.unique); per combination, the estimate formatted '#,##0' or '#,##0"*"', or '..' or '-'; freeze at get_column_letter(len(rows) + 1) + '2'.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A cross table is the long table pivoted, cell by cell, with each cell's reliability turned into how it is shown: a formatted number when there is one to show, a symbol when there is not.
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 cross_sheet(workbook: openpyxl.Workbook, title: str, table: pd.DataFrame, rows: list, column: str): """Add a sheet called `title`: the `rows` variables down the side, the categories of `column` across the top, each cell its estimate (formatted, with an asterisk for caution) or a symbol (.. suppressed, - no sample). Returns it.""" # Exercise S2.6: the task and examples are in the text above this cell. sheet = workbook.create_sheet(title) across = list(pd.unique(table[column])) sheet.append([*rows, *across]) for cell in sheet[1]: cell.font = Font(bold=True) cells = table.set_index([*rows, column]) for keys in table[rows].drop_duplicates().itertuples(index=False): sheet.append(list(keys)) line = sheet.max_row for offset, category in enumerate(across, start=len(rows) + 1): where = (*keys, category) if where not in cells.index: sheet.cell(row=line, column=offset, value=SYMBOLS["no sample"]) continue found = cells.loc[where] if found["reliability"] in SYMBOLS: sheet.cell(row=line, column=offset, value=SYMBOLS[found["reliability"]]) else: written = sheet.cell(row=line, column=offset, value=float(found["est"])) written.number_format = CAUTION_FORMAT if found["reliability"] == "caution" else NUMBER_FORMAT sheet.freeze_panes = f"{get_column_letter(len(rows) + 1)}2" return sheetWhy each part is there
pd.uniqueanddrop_duplicateskeep the order the table already has, whichlabeled_cellsand S2.4 made the categories' order. Apivotorgroupbywould sort the categories by text and putFemalebeforeMaleandTotalbefore the provinces that come after it in the alphabet.- Indexing the table by
[*rows, column]turns each cell into one lookup by its keys. A combination the table lacks is not in the index, and the sheet shows it as-, aslabeled_cellsshows an empty cell, so a table straight from svy, without the grid, still lays out right. - The caution mark is in the number format, so the cell keeps its number and a reader's formula still adds it. A suppressed cell holds
..and no number at all: with the number in the cell and a symbol only in its format, the estimate would still be published. - The panes freeze below the header and right of the row labels, so both stay in view as a reader scrolls a three-way table.
Stretch S2.7. Flag and suppress by CV
The task
Why it matters: a flag computed by hand in Excel is a step someone forgets on the next batch. Computed by the script, from thresholds set in one place, it is there every time, and the notes sheet can count the flags.
Input → output: a sheet as module 7's table_sheets gives it (the level and the domain's codes, estimate, se, cv, lci, uci, unweighted, n), and the two thresholds → a copy of the sheet with a new column flag and the unreliable estimates removed:
| estimate | se | cv | lci | uci | → flag | → estimate, se, lci, uci |
|---|---|---|---|---|---|---|
| 100 | 5 | 0.05 | 90 | 110 | "" (empty text) |
as they were |
| 200 | 40 | 0.20 | 120 | 280 | "" |
as they were |
| 300 | 75 | 0.25 | 150 | 450 | "caution" |
as they were |
| 500 | 200 | 0.40 | 100 | 900 | "suppress" |
missing |
| 0 | 0 | missing, or infinite | missing | missing | "suppress" |
missing |
A CV equal to a threshold stays in the lower band, as in S2.3: 0.20 has no flag, 0.35 is caution. unweighted and n stay as they are. The input sheet must not change.
Tools: np.select(conditions, choices, default=...) from module 5, .copy(), and .loc[rows, columns] = np.nan.
If the check is red
np.select([cv <= caution, cv <= suppress], ['', 'caution'], default='suppress') on a copy; then estimate, se, lci and uci missing where the flag is 'suppress'.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Three bands from two thresholds, tested from the most reliable down; whatever passes neither test, a missing CV included, falls to the default, "suppress", whose estimate, SE and interval are then removed.
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_cv_flags(table: pd.DataFrame, caution: float, suppress: float) -> pd.DataFrame: """A copy of the sheet with `flag`: "" up to `caution`, "caution" above it up to `suppress`, "suppress" above `suppress` or without a finite CV; estimate, se, lci and uci are missing where the flag is "suppress".""" # Exercise S2.7: the task and examples are in the text above this cell. flagged = table.copy() flagged["flag"] = np.select([flagged["cv"] <= caution, flagged["cv"] <= suppress], ["", "caution"], default="suppress") flagged.loc[flagged["flag"] == "suppress", ["estimate", "se", "lci", "uci"]] = np.nan return flaggedWhy each part is there
table.copy()keeps the caller's sheet as it was: the same estimates may be published with other thresholds, or checked again.np.selecttakes the first condition that holds, socv <= suppressonly meets rows that already failedcv <= caution: those are the caution band.<=keeps a CV equal to a threshold in the lower band.- A missing CV compares as False with any number, and an infinite one is above every threshold, so both fail the two tests and get the default "suppress". Testing
cv > suppressfor suppress instead would leave a missing CV with no flag at all. - The SE and the interval go with the estimate: with the CV published, the SE gives the estimate back (SE / CV), and the interval's middle is the estimate.
unweightedandndescribe the sample, so they stay.
Stretch S2.8. Refuse a missing region
The task
Why it matters: this function is the difference between a script that stops and says "region 04 is missing" and one that publishes the total above. Its default is to refuse; accepting a partial run takes a flag someone has to type.
Input → output: the flat table (one row per household, with region_code as zero-padded text), the list of expected regions, and allow_missing → the expected regions that have at least one row in the table, in the order of expected:
| the table's region_code values | expected | allow_missing | result |
|---|---|---|---|
| 01, 04, 07 | 01, 04, 07 | False | ["01", "04", "07"] |
| 07, 01, 7, 13 | 01, 04, 07 | False | raises MissingRegions(["04"]) |
| 07, 01, 7, 13 | 01, 04, 07 | True | ["01", "07"] |
Only the expected codes count: 7 is not region 07 (module 2 keeps codes as zero-padded text), and 13 is not a region this survey expects. Rows like those are not this function's to judge: their strata have no count in stratum_counts.csv, so the check of S2.9 stops them.
Tools: .isin or set from Arrays & DataFrames; a list comprehension over expected; raise MissingRegions(missing).
If the check is red
Go through the expected regions, keep the ones with rows in the table, and raise MissingRegions(missing) when some are missing and allow_missing is False.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Go through the regions the survey expects and look for each in the table, rather than taking whatever codes the table holds; refuse unless a partial run was asked for.
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 regions_to_read(flat: pd.DataFrame, expected: list[str], allow_missing: bool) -> list[str]: """The expected regions with at least one row in the flat table, in the order of `expected`. Raises MissingRegions naming the others, unless allow_missing is True.""" # Exercise S2.8: the task and examples are in the text above this cell. found = set(flat["region_code"]) present = [region for region in expected if region in found] missing = [region for region in expected if region not in found] if missing and not allow_missing: raise MissingRegions(missing) return presentWhy each part is there
- Looping over
expectedfinds exactly the regions the survey should have, in its order. Taking the table's own codes (unique()) would count7and13as regions, and say nothing of the one that is missing. - The missing list is what the refusal names: the person running the script learns which region's database to add to the flat table.
if missing and not allow_missingmakes refusing the default;--allow-missingis the one way to accept a partial run, and the command then logs the regions left out and writes them into the workbook's notes sheet.
Stretch S2.9. Sampled units against the population, by stratum
The task
Why it matters: this check catches a household counted twice in a stratum that takes every unit, a stratum stratum_counts.csv lacks, and counts from another round, before any estimate is computed. A sampling unit holds many households, so counting rows here would flag every area stratum that is fine.
Input → output: a design frame (one row per household, with stratum_id, psu_id and psus_in_stratum) → one row per stratum, sorted by stratum:
| stratum_id | psus_sampled | psus_in_stratum | ok |
|---|---|---|---|
| A-1 | 2 | 2 | True |
| A-2 | 3 | 2 | False |
| B-1 | 2 | missing | False |
psus_sampled: the number of different sampling units in the stratum's rows, not the number of rows;psus_in_stratum: the stratum's count of sampling units, from its rows;ok: True whenpsus_sampledis no larger thanpsus_in_stratum; False when it is larger, or the count is missing.
Tools: groupby("stratum_id").agg(...) with "nunique" and "first", from Arrays & DataFrames; a comparison makes the ok column.
If the check is red
Group by stratum_id; psus_sampled counts the different psu_id values (nunique), not the rows; ok is psus_sampled <= psus_in_stratum.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. 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 different sampling units of each stratum, not its rows, and compare with the stratum's count; a missing count fails the comparison, so it fails the check.
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 stratum_check(frame: pd.DataFrame) -> pd.DataFrame: """One row per stratum: psus_sampled (different sampling units in the frame), psus_in_stratum and ok, True when the sample holds no more sampling units than the population.""" # Exercise S2.9: the task and examples are in the text above this cell. table = frame.groupby("stratum_id").agg(psus_sampled=("psu_id", "nunique"), psus_in_stratum=("psus_in_stratum", "first")).reset_index() table["ok"] = table["psus_sampled"] <= table["psus_in_stratum"] return tableWhy each part is there
("psu_id", "nunique")counts the different sampling units. An area stratum holds a dozen or more households per drawn area, so"size"would count four areas as fifty households and flag a stratum that is fine.("psus_in_stratum", "first")takes the stratum's count from its first row: every row of a stratum carries the same one.psus_sampled <= psus_in_stratumis False when the count is missing, as any comparison with a missing value is: a stratumstratum_counts.csvlacks fails, which is right, since svy could not correct it either.
Stretch S2.10. A manifest of files
The task
Why it matters: with the manifest, "did the second run change anything?" is answered by comparing two small tables, and "which data were these tables made from?" by reading one.
Input → output: a list of file paths and a folder they are all in (root) → one row per file, sorted by file:
| file | fingerprint |
|---|---|
run1/national.csv |
the SHA-256 of the file's bytes |
run1/tables.xlsx |
the SHA-256 of what the workbook holds: each sheet's title and each row's values |
file: the path relative toroot, written with/(path.relative_to(root).as_posix()), so the manifest reads the same in any folder and on any computer;fingerprint: for a workbook (.xlsx), the hash of its contents, read with openpyxl; for any other file, the hash of its bytes.
For the workbook, openpyxl.load_workbook(path, read_only=True) opens it; workbook.worksheets are its sheets, sheet.title a sheet's name and sheet.iter_rows(values_only=True) its rows as tuples of values. Put them in one list, turn it into text with repr(...), and hash text.encode("utf-8"). Close the workbook after reading (workbook.close()).
Tools: hashlib.sha256(...).hexdigest(), Path.read_bytes, Path.suffix, Path.relative_to, openpyxl as above, and pd.DataFrame(rows).
If the check is red
Hash a workbook's sheet titles and values (openpyxl, values_only=True), any other file's bytes; file is relative to root with as_posix(); sort by file.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Fingerprint what must stay the same between runs: a CSV file's bytes, but a workbook's sheets and values, since its bytes record when it was saved.
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 manifest(paths: list[Path], root: Path) -> pd.DataFrame: """One row per file, sorted by file: its path relative to root (with /) and its fingerprint, the SHA-256 of its bytes, or for a workbook of what it holds (each sheet's title and rows of values).""" # Exercise S2.10: the task and examples are in the text above this cell. rows = [] for path in map(Path, paths): if path.suffix == ".xlsx": workbook = openpyxl.load_workbook(path, read_only=True) content = repr([(sheet.title, list(sheet.iter_rows(values_only=True))) for sheet in workbook.worksheets]).encode("utf-8") workbook.close() else: content = path.read_bytes() rows.append({"file": path.relative_to(root).as_posix(), "fingerprint": hashlib.sha256(content).hexdigest()}) return pd.DataFrame(rows).sort_values("file", ignore_index=True)Why each part is there
- A workbook's bytes include the moment it was saved, so two runs never give the same ones. Its titles and values are what a reader reads, and they are the same when the tables are.
reprof the list of (title, rows) is one text that changes when any title, cell value or row order changes; any such text would do, as long as every run makes it the same way.read_bytes()hashes a CSV exactly as written.read_text()would let Python translate line endings on the way in, so the fingerprint could differ from the file's.relative_to(root).as_posix()keeps the folder the run happened in out of the manifest: two runs in two folders, or on Windows and Linux, give the same rows.- Sorting by
filemakes the manifest's order its own, not the order the files were listed in.
Stretch S2.11. A chart of the CVs
The task
Why it matters: a reader takes in at a glance which provinces have reliable figures, which no table of CVs gives.
Input → output: a long table of one level's estimates (a row per domain and indicator, with domain, indicator and cv) and the name of an indicator → a bar chart with one bar per domain of that indicator, its length the CV in percent (a CV of 0.2957 is a bar of 29.57). The rows of the check's small made-up table:
| domain | indicator | cv | → bar |
|---|---|---|---|
| La Union | households running a large-scale unit | 0.2957 | 29.57 |
| Pangasinan | households running a large-scale unit | 0.2509 | 25.09 |
| La Union | fishing households | 0.0334 | (another indicator: no bar) |
Draw it with matplotlib, seaborn or Altair; horizontal or vertical bars both pass. Give it a title and label the CV axis with its unit; lines at the two thresholds help the reader, and the check ignores them. Return the chart: ax for matplotlib or seaborn, the chart for Altair.
Tools: a filter on indicator, cv * 100, and a bar chart: ax.barh(...) (Arrays & DataFrames, module 7), sns.barplot, or alt.Chart(...).mark_bar(); ax.axvline(x) for a threshold line.
If the check is red
Keep the indicator's rows only; one bar per domain, its length cv * 100; return ax (or the Altair chart).
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Keep one indicator's rows, then draw a bar per domain whose length is its CV in percent, with the thresholds as reference lines so the reader sees which bars cross them.
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 cv_chart(table: pd.DataFrame, indicator: str): """A bar chart of one indicator's CVs: one bar per domain, its length the CV in percent. Returns the chart.""" # Exercise S2.11: the task and examples are in the text above this cell. rows = table[table["indicator"] == indicator] fig, ax = plt.subplots(figsize=(6.5, 0.4 * len(rows) + 1.2)) ax.barh(rows["domain"], rows["cv"] * 100, color="#4c78a8") for threshold, label in ((CAUTION_CV, "caution above"), (SUPPRESS_CV, "suppress above")): ax.axvline(threshold * 100, color="#888888", linewidth=0.8, linestyle="--") ax.annotate(f"{label} {threshold:.0%}", (threshold * 100, 1), xycoords=("data", "axes fraction"), fontsize=8, color="#555555", va="bottom", ha="center") ax.invert_yaxis() # the first domain at the top, as in the table ax.set_xlabel("coefficient of variation (%)") ax.set_title(f"{indicator.capitalize()}: CV of each estimate", loc="left") ax.spines[["top", "right"]].set_visible(False) fig.tight_layout() return axWhy each part is there
- Filtering on
indicatorfirst: the table holds every indicator, so without it each province would get four bars on one line. cv * 100puts the bars in percent, the unit the axis label states and the reader thinks in; the thresholds are drawn in the same unit.- Horizontal bars leave room for province names; the check reads a bar's domain and length whichever way it runs.
axvlinelines are drawn across the chart, not as data, so they help the reader without changing what the chart says.