Every exercise in 96_primer_survey_sampling.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 P2.1. Population counts from sampling fractions
The task
Why it matters: a design written for R with fractions runs in svy only once each fraction is a count. Done wrong, svy runs without complaint and every standard error is off.
Input → output: a sample with the columns stratum, psu and fpc (the sampling fraction of PSUs, the same on every row of a stratum) → a column named psu_population, one value per row, with the same row labels: the stratum's distinct PSUs divided by its fraction. Some rows of the sample above:
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| 17.5 for stratum A of the sample, not 10 | The households are counted, not the distinct PSUs (7 ÷ 0.4). | step 1: "nunique" on psu |
| 4 rows instead of 18 | The counts are per stratum, from agg or nunique() after groupby, not one per row. |
step 1: transform("nunique") keeps every row |
| Wrong counts in the small table only | Distinct PSUs counted over the whole table, so "1" of stratum A and "1" of stratum C are one PSU. |
step 1: group by stratum first |
| 1.6 or 0.1 for stratum A | The fraction multiplied by n, or divided by it. | step 2: n ÷ fpc |
| The values are right, the check red | The column is not named psu_population, or the row labels were reset. |
step 3: .rename("psu_population"); no reset_index |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A sampling fraction is n ÷ N, so N is n ÷ fraction, with n the number of PSUs drawn in the stratum: distinct PSUs, not households, and counted within the stratum.
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 psu_counts(sample: pd.DataFrame) -> pd.Series: """Each row's stratum population of PSUs, N = n ÷ f, with n the stratum's distinct PSUs in the sample.""" # Exercise P2.1: the task and examples are in the text above this cell. drawn = sample.groupby("stratum")["psu"].transform("nunique") return (drawn / sample["fpc"]).rename("psu_population")Why each part is there
groupby("stratum")["psu"].transform("nunique")counts each stratum's distinct PSUs and puts the count on every row of that stratum, so it lines up withfpcrow by row.nunique, notsize: the fraction is a fraction of areas, and an area holds many households. Counting rows makes stratum A of the example 7 ÷ 0.4 = 17.5 instead of 10.- Counting within the stratum matters because PSU names repeat across strata. Counting distinct PSUs over the whole table would merge area 1 of one stratum with area 1 of another.
- The division may leave a trace of rounding, 44.99999999999999 for 45: svy takes it as it is, and the check rounds to six decimals.
- The result keeps the sample's row labels, so
sample.assign(psu_population=psu_counts(sample))puts each value on its row.
Exercise P2.2. A stratified total, its SE and CV, without svy
The task
Why it matters: a function you wrote from the formula is how you confirm a library's number, and how you compute one the library does not offer. Module 6 builds on it for the ReGenesees calls no Python library implements.
Input → output: a sample with the columns stratum, psu, psu_population and weight, and the name of the variable y → a dictionary with three numbers:
| key | what it is |
|---|---|
"total" |
Σ w·y over every row |
"se" |
the square root of the variance formula above |
"cv" |
se ÷ total |
For the sample of part 2 it returns the numbers of the cells above. Two rules the formula needs: a stratum with a single PSU adds nothing to the variance (svy's singleton="skip"), and PSU names can repeat in different strata, so a PSU is its stratum and its name together. Weights may differ within a PSU, as calibrated weights do.
Tools: the cell above, written as a function: groupby(["stratum", "psu"]) for the PSU totals, then a loop over the strata, or a second groupby; np.sqrt.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| The total right, the SE far too small | The variance is computed from households, not from PSU totals. | step 2: one row per PSU first |
| The second case red, the first green | PSUs grouped by psu alone, so areas of different strata that share a name are added together. |
step 2: groupby(["stratum", "psu"]) |
ZeroDivisionError, or nan for the SE in the third case |
A stratum with one PSU reaches n / (n - 1). |
step 3: only strata with n > 1 |
| The SE a little too large | The fpc is missing: every stratum's part is too large, and stratum F adds variance it should not. | step 3: (1 - n / N) |
| The SE too small by a factor near 1.2 to 1.7 | n / (n - 1) is missing, or np.var with its default ddof=0 used. |
step 3: n / (n - 1) times the sum of squares |
| The cv 100 times too large | The CV given in percent. | step 4: se / total, a fraction as svy gives it |
| KeyError: 'members' | The variable's name typed in instead of taken from y. |
sample[y] |
Still stuck after ten minutes? Ask your table, then raise your hand.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
The formula, written down: weighted totals per PSU, their spread within each stratum scaled by n/(n−1) and by the fpc, the strata's parts added, a square root.
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 stratified_total(sample: pd.DataFrame, y: str) -> dict: """The estimated total of y under a stratified cluster design, with its standard error and coefficient of variation.""" # Exercise P2.2: the task and examples are in the text above this cell. weighted = sample.assign(wy=sample["weight"] * sample[y]) total = weighted["wy"].sum() psus = weighted.groupby(["stratum", "psu"], as_index=False).agg(t=("wy", "sum"), N=("psu_population", "first")) variance = 0.0 for _, stratum in psus.groupby("stratum"): t, n, N = stratum["t"].to_numpy(), len(stratum), stratum["N"].iloc[0] if n > 1: variance += (1 - n / N) * n / (n - 1) * np.sum((t - t.mean()) ** 2) se = float(np.sqrt(variance)) return {"total": float(total), "se": se, "cv": se / float(total)}Why each part is there
wy = weight × yturns each household into the number of population units it stands for; the total is their sum, the same as svy'sest.- Grouping by
["stratum", "psu"]makes one row per PSU. Grouping bypsualone would add together areas of different strata that share a name, and the variance would be computed from totals that are no PSU's. - The variance is computed from PSU totals, not from households: the areas, not the households, were drawn, so only their differences measure what another draw would change.
n / (n - 1) * ((t - t.mean()) ** 2).sum()is the stratum's spread of PSU totals, and1 - n / Nits fpc. A stratum taken whole gets 0 from the fpc; a stratum with one PSU is skipped, assingleton="skip"does, sincen - 1would be 0.- Strata are drawn independently, so their variances add; the SE is the square root of the sum, and the CV divides it by the total.