Skip to content
Learn Python with BNHR

Module 6: Estimate under the survey design

On this page
  1. Overview
  2. 6.1 · The rows the design can use, and its lonely PSUs
  3. 6.2 · Population counts from sampling fractions
  4. 6.3 · A stratified total and its SE, from the formula
  5. 6.4 · A table by province, with svy
  6. 6.5 · Every cell of a cross table
  7. 6.6 · A domain mean, from the formula
  8. 6.7 · Weighted estimates and the sample's counts, side by side at three levels
  9. 6.8 · A ratio of two totals, from the formula
  10. 6.9 · Linear calibration, from the formula

Every exercise in 50_design_estimates.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 6.1. The rows the design can use, and its lonely PSUs

The task

Why it matters: this is the step before a design is declared, in any language. Keep the rows that have a final weight, a stratum and a cluster id (sel_final_weight, sel_stratum and psu_id), then set the lonely-PSU rule. A row without a weight stands for no household, and a row without a stratum or a PSU has no place in the variance formula. The lonely PSUs are found after those rows are dropped: dropping a household can leave its stratum with one area.

Input → output: a frame of households with sel_stratum, stratum_id, psu_id and sel_final_weight → the rows the design can use, in the frame's order, every column kept, with one new column, lonely_psu:

  • a row is kept when sel_final_weight, sel_stratum and psu_id all have a value;
  • lonely_psu is True on every kept row of a stratum that has one PSU among the kept rows, and False on the others.
region_code hh_id stratum_id psu_id sel_final_weight → kept → lonely_psu
01 1 X-A 1 2.5 yes False: X-A keeps PSUs 1 and 2
01 4 Y-A 1 2.5 yes True: Y-A's other PSU had one household, with no weight
01 5 Y-A 2 missing no
04 1 missing missing 1.0 no: no stratum
04 2 Z-C missing 15.0 no: no PSU
04 3 Z-C 7 15.0 yes True

The rows of a lonely stratum stay: they are part of every estimate. singleton="skip", like ReGenesees' "remove", leaves out only their stratum's share of the variance, and lonely_psu names the rows that share comes from, for the notes of a table.

Tools: .notna() and & for the rows to keep; groupby("stratum_id")["psu_id"].transform("nunique") (module 5's transform) gives each row its stratum's count of PSUs; assign.

If the check is red: common causes

what you see the usual cause look at
Y-A and Z-C not lonely The PSUs were counted before the rows were dropped. drop first, then transform("nunique") on the kept rows
The row with no weight, or no PSU, is still there One of the three tests is missing. sel_final_weight, sel_stratum and psu_id, each .notna()
The lonely strata's rows are gone Their rows were dropped, as if "remove" dropped households. keep them, with lonely_psu True
lonely_psu True on one row per stratum The count was taken with groupby(...).nunique() and joined back wrongly, or only the first row marked. transform: one value per row
TypeError or ValueError on & The tests were joined with and, which wants single values. &, with each test a column of True and False

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 6.2. Population counts from sampling fractions

The task

Why it matters: this is the first line of any translation of an R design to svy. Get n wrong (households instead of PSUs) and the fpc is wrong in every stratum, silently: svy takes any count of at least n.

Input → output: a frame with stratum_id, psu_id and a column of sampling fractions (its name is the argument fraction) → a column of whole numbers, one per row, each row's stratum's population count N = n / f:

stratum_id psu_id fraction → N
S-A 1, 2, 3, 4 (several households each) 0.4 10
S-F one per household, 4 households 1 4
S-C 10 PSUs 0.0667 (10 of 150, written to four decimals) 150

The last row is why the result is rounded to a whole number: 10 / 0.0667 is 149.93. It is this survey's own stratum C.

Tools: groupby(...)["psu_id"].transform("nunique") (module 5's transform), division, .round() and .astype("int64").

If the check is red: common causes

what you see the usual cause look at
28 for the four-area stratum, thousands for the survey's stratum C Households divided by the fraction, not PSUs. transform("nunique") on psu_id
149 for the stratum of 0.0667 The decimals were cut, not rounded. .round() before .astype("int64")
One number for the whole table nunique() without transform: one count, not one per row. groupby("stratum_id")["psu_id"].transform("nunique")
KeyError: 'fraction' on the last check The column name was written in, not taken from the argument. frame[fraction]

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 6.3. A stratified total and its SE, from the formula

The task

Why it matters: this formula is under every SE this course prints. Written once from the formula, it shows what the library does, it is what you check a library against, and section 4 builds every other estimator on it.

Input → output: a frame with stratum_id, psu_id, psus_in_stratum and sel_final_weight, and the name of a column y → a Series with three values, labeled est, se and cv:

est se cv
the small design below, y 40 7.4833 0.1871

The small design has a take-all stratum T (3 households, each its own PSU, N = 3, weight 1, y = 2, 5, 1) and a stratum S of 3 PSUs out of N = 6, every weight 4: PSU s1 holds y = 1 and 0, s2 holds 3, s3 holds 1, 1 and 2. Work it by hand once: T adds 8 to the total and nothing to V; S's PSU totals are 4, 12 and 16.

Tools: a column of w·y (assign), groupby(["stratum_id", "psu_id"]).agg(...) for the PSU totals, groupby("stratum_id")[...].transform("size") and transform("mean") for n_h and t̄_h, then the formula.

If the check is red: common causes

what you see the usual cause look at
se far too small on the survey The spread of households, not of PSU totals. group by ["stratum_id", "psu_id"] before the spread
se of 10.58 on the small design The fpc left out. (1 - n / N)
se of 6.11 on the small design Divided by n, not n − 1: the n / (n − 1) factor is missing. n / (n - 1)
se of 0 or nan Every stratum skipped, or n counted as households so that the fpc turned negative. transform("size") on the PSU table
est too small by the weights The values summed, not w·y. frame["sel_final_weight"] * frame[y]
KeyError: 'est' The result is not labeled est, se, cv. pd.Series({"est": ..., "se": ..., "cv": ...})

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 6.4. A table by province, with svy

The task

Why it matters: this is the table a report prints: one row per province, the estimate, its SE, its CV as a percentage, and its 95% confidence interval. Module 7 writes tables like it to a workbook.

Input → output: a svy Sample whose data has a province column, and the name of a column y → a pandas DataFrame, one row per province in order of name, with the columns:

province est se cv_pct lci uci
Batangas … … 29.9 … …

cv_pct is the CV in percent: svy's cv is a fraction, so 0.299 is 29.9.

Tools: sample.estimation.total(y=..., by=...), .to_polars(), .to_pandas(), a new column, and the column list.

If the check is red: common causes

what you see the usual cause look at
cv_pct below 1 svy's fraction kept as it is. result["cv"] * 100
One row, no province by= left out: the total of all provinces. by="province"
UnknownNameError: Estimate.to_pandas does not exist [UNKNOWN_NAME] A result is not a table; convert it first. .to_polars().to_pandas()
Extra columns (df, n) The column list was not applied. [["province", "est", "se", "cv_pct", "lci", "uci"]]
Rows in another order Not sorted. .sort_values("province")

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 6.5. Every cell of a cross table

The task

Why it matters: ask svy for the operators by province and sex, and it returns one row per combination that holds a sampled operator. A province whose sample has no operator with an invalid sex code gets no row for it; if a region's database lost its women operators, their rows would vanish the same way. A cell nobody fell into is still a cell: its estimate is 0 and it has no sampling error to report.

Input → output: a svy sample, the name of a column y to total, and levels, a dictionary from each domain variable to its categories in order (one variable, two, or three) → one row per combination of the categories, in the order itertools.product would list them, with the columns: the domain variables, est, se, cv and n:

  • a combination svy returned: its est, se, cv and n;
  • a combination svy did not return: est 0, se 0, cv missing, n 0.

The checks' small table has nine operators in provinces P and Q, and none in R or with an invalid sex code; the accordion under this exercise shows it. Its first rows:

domain_cells(operator_sample(small_operators()), "operators", {"province": ["P", "Q", "R"], "sex": ["Male", "Female", INVALID]})
province sex est se cv n
P Male 9.0 2.83 0.314 3
P Female 4.0 2.83 0.707 1
P Invalid value 0.0 0.0 missing 0
Q Male 13.0 4.90 0.377 4
Q Female 1.0 0.0 0.000 1
…
R Invalid value 0.0 0.0 missing 0

Q's woman is in the take-all stratum T: an estimate with no sampling error, a CV of 0.

Tools: sample.estimation.total(y=..., by=[...]) and .to_polars().to_pandas() (Exercise 6.4), itertools.product(*lists) for every combination, pd.DataFrame(..., columns=...), merge(..., how="left", validate=...) (module 3), and fillna.

If the check is red: common causes

what you see the usual cause look at
Fewer rows than combinations svy's result returned as it is: it has no row for an empty cell. the grid, merged how="left"
The right rows in another order svy sorts its result by text (Female before Male): the grid was merged onto svy's rows instead of the other way round, or built from the data's categories. grid.merge(found, ...), the grid from levels
est missing in empty cells, or n a decimal The grid's empty rows left as NaN, or n filled but not turned back into whole numbers. fillna(0.0); fillna(0).astype("int64")
The SEs are smaller than svy's The rows were filtered to each domain before estimating. by= on the full sample
KeyError naming a domain variable by was given the dictionary's values, or one name as text where a list is needed. by=list(levels)

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 6.6. A domain mean, from the formula

The task

Why it matters: "how many members does a household that runs a large-scale unit have, on average?" is a mean over a domain, and the domain is the trap: the right answer keeps every row and lets the households outside the domain count as zeros in the linearized variable. Written once, it is how svy's mean(..., where=...) works.

Input → output: a frame, the name of a column y, and a boolean Series domain (one value per row, True in the domain) → a Series labeled est and se:

1[d]   1 for a row in the domain, 0 outside
N̂_d   = Σ w · 1[d]                    the households the domain stands for
m_d    = Σ w · 1[d] · y / N̂_d          the domain mean
z      = w · 1[d] · (y − m_d) / N̂_d    0 for every row outside the domain
SE     = √ taylor_variance(frame, z)

Tools: the formula above, with taylor_variance (shown above).

If the check is red: common causes

what you see the usual cause look at
est right, se too small The frame filtered to the domain before the variance: the PSUs with no member are gone. z on every row, taylor_variance(frame, z)
est too small Divided by all households' weights, not the domain's. N_d = (w * d).sum()
se many times too large z left as w·d·y, the domain total's variable, not the mean's. (y − m) / N_d
TypeError on the domain The True/False Series used in arithmetic as it is. np.asarray(domain, dtype=float)

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 6.7. Weighted estimates and the sample's counts, side by side at three levels

The task

Why it matters: this is the summary step. Every table is made national, regional and provincial, and each weighted estimate sits beside the sample's own figures: the sum of the same variable over the interviewed households, and the number of interviews behind it.

If the check is red: common causes

what you see the usual cause look at
unweighted equals weighted The weights were multiplied in before the sum: that is the weighted total again. frame.groupby(by)[y], y alone
interviews equals unweighted for units or operators The count is of y's sum, not of rows. "size"
ValueError: No group keys passed! on the national level frame.groupby([]): the national level has no column to group by. one row of frame[y].sum() and len(frame)
MergeError: No common columns to perform merge on The national row merged with no on=. how="cross" when by is empty
Fewer rows than expected, or the national row missing A level skipped, or its table left out of the concat. every level of LEVELS, each table added to the list

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Exercise 6.8. A ratio of two totals, from the formula

The task

Why it matters: ratios are most of a fisheries report: boats per unit, catch per trip, large-scale units as a share of all. Writing one shows why its SE is not the SE of the numerator divided by the denominator.

Input → output: a frame and the names of two columns y and x → a Series labeled est and se. On the small design of Exercise 6.3, y over x is 0.8333 with an SE of 0.1543.

Tools: the formula above, with taylor_variance.

If the check is red: common causes

what you see the usual cause look at
est a little off The mean of each row's y / x, not the ratio of the totals. Y / X
se thousands of times too large z not divided by X̂. / X
se far too large, est right z = w·y: the SE of the numerator's total. y − R·x
ZeroDivisionError or inf A row's y / x with x = 0, from dividing row by row. divide the totals

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 6.9. Linear calibration, from the formula

The task

Why it matters: calibration is how a survey's weights are made to agree with what is known, and the linear case is under every other: raking and the logit distance below are iterations of the same solve. Written once, the weights a survey publishes are no longer a black box.

Input → output: the starting weights d (one per row), the auxiliaries X (a table or 2-D array, one row per row of d, one column per known total) and the known totals (one per column of X) → a numpy array of calibrated weights, one per row:

d x (class) → calibrated
1, 1 class 1, known total 4 2, 2
2, 2, 2 class 2, known total 9 3, 3, 3

With one 0/1 column per class, calibration is poststratification: every weight of a class is multiplied by its known total over its weighted count (4 / 2 and 9 / 6).

Tools: np.asarray(..., dtype=float), @ (matrix product), [:, None] to multiply each row of X by its weight, and np.linalg.solve.

If the check is red: common causes

what you see the usual cause look at
The weights come back unchanged λ solved against the totals, not the gap. totals - X.T @ d
ValueError: matmul: Input operand ... has a mismatch X's rows multiplied by d as a row, not a column. X * d[:, None]
Weights of 2 and 1.5 instead of 2 and 3 The factor g returned, not the weight. d * (1 + X @ lam)
LinAlgError: Singular matrix Two columns of X that say the same thing: a 0/1 column for every class and an intercept. X's columns

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 capstone
CapstoneCapstone
AboutThe capstone of Python Essentials, after module 7: in groups, a report on three barangays from their records, from the file to a written summary. Its sections and its notebook to read on the web.
CoursePython Essentials, free