Skip to content
Learn Python with BNHR

Stretch: tabulation

On this page
  1. Overview
  2. S2.1 · Fishing units by species label, in polars
  3. S2.2 · The design effect of a total, from the formula
  4. S2.3 · Publish, caution or suppress
  5. S2.4 · Margins from their own estimates
  6. S2.5 · A proportion and its confidence interval
  7. S2.6 · The cross table as a reader sees it
  8. S2.7 · Flag and suppress by CV
  9. S2.8 · Refuse a missing region
  10. S2.9 · Sampled units against the population, by stratum
  11. S2.10 · A manifest of files
  12. S2.11 · A chart of the CVs

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.

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.

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.

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.

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.

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 of column in the order it first appears in the table, all bold;
  • one row per combination of the rows variables, in the order it first appears in the table: the combination's values, then one cell per category of column, 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: B2 with one variable down the side, C2 with 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.

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.

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.

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 when psus_sampled is no larger than psus_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.

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 to root, 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.

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.

Something new

Identify results
LayerExplore a glossary
GlossaryGlossary
AboutThe glossary of Python for Data Management, for any time: the words the course uses, in plain language, each with where you meet it.
CoursePython for Data Management, free