Every exercise in 95_primer_r_to_python.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 P1.1. Areas and households by province
The task
Why it matters: a fieldwork report starts with how many areas were visited and how many households were interviewed in each province. In R you write
households |>
filter(sel_stratum != "F") |>
group_by(region_code, province_code) |>
summarise(households = n(), areas = n_distinct(sel_ea), members = sum(hh_roster_members), .groups = "drop")
and this exercise is its Python version.
Input → output: the households table → one row per province of the area strata A, B and C (a province is named by its region and province codes together, as module 1 sets out), with five columns:
| region_code | province_code | households | areas | members |
|---|---|---|---|---|
| 01 | 033 | … | … | … |
| … | … | … | … | … |
households: how many households;areas: how many distinct areas (sel_ea);members: the sum ofhh_roster_members.
Key columns or index, either passes: the check reads both.
Tools: a mask with !=; groupby([...], as_index=False) and .agg() with named results, "size", "nunique" and "sum" (above). In polars, the same with group_by and pl.len(), n_unique(), sum(), and .to_pandas() at the end.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
households and members too large, areas right (6 households, not 4, for province 033 in the small table) |
Stratum F is still in. Its households have no area, so nunique skips them, but they are counted as households and members. |
step 1: households["sel_stratum"] != "F" |
areas equals households |
The areas are counted with "size" or "count", one per row. |
step 3: ("sel_ea", "nunique") |
No region_code column, or a KeyError about it |
The groups use province_code alone. |
step 2: groupby(["region_code", "province_code"]) |
| ValueError: The truth value of a Series is ambiguous, or TypeError: operation 'rand_' not supported | Two conditions joined with and (the first error), or with & but without brackets (the second). |
one condition is enough here; for two, (a) & (b) (part 9) |
| AttributeError: 'SeriesGroupBy' object has no attribute 'n' | R's names used as pandas' function names. | "size", "nunique", "sum" |
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 R chain read step by step: the same filter as a mask, the same two keys for the groups, and R's n(), n_distinct() and sum() as pandas' "size", "nunique" and "sum".
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 areas_by_province(households: pd.DataFrame) -> pd.DataFrame: """One row per province of the area strata A, B and C: households, distinct areas (sel_ea) and members.""" # Exercise P1.1: the task and examples are in the text above this cell. areas = households[households["sel_stratum"] != "F"] return areas.groupby(["region_code", "province_code"], as_index=False).agg( households=("hh_id", "size"), areas=("sel_ea", "nunique"), members=("hh_roster_members", "sum"), )Why each part is there
households[households["sel_stratum"] != "F"]isfilter(sel_stratum != "F"). Without it, the households of stratum F, taken from the register and not from an area, are counted with the households and members of the areas.- The groups need both keys, as in
group_by(region_code, province_code): the course names a province by its region and its province code together, so the result carries both. ("hh_id", "size")counts rows, R'sn(). Any column would do, sincesizecounts every row.("sel_ea", "nunique")isn_distinct(sel_ea)."count"there would count households again, one per row, not areas.as_index=Falsekeeps the keys as columns, as a tibble has them. The check accepts them in the index too.
The polars version reads the same: pl.from_pandas(households).filter(pl.col("sel_stratum") != "F").group_by("region_code", "province_code").agg(households=pl.len(), areas=pl.col("sel_ea").n_unique(), members=pl.col("hh_roster_members").sum()).to_pandas().
Exercise P1.2. Weighted totals and means by domain, without svy
The task
Why it matters: every estimate in the course's tables starts as a weighted sum. Writing it yourself is how you know what svy's est column is, and how you check a number when R and Python disagree.
Input → output: a table of households, the name of a variable y, the name of a column by that defines the domains, and the name of the weight column ("sel_final_weight" unless another is given) → one row per domain, with four columns:
by column |
households | total | mean |
|---|---|---|---|
| 01 | … | Σ w·y over the domain | total ÷ Σ w over the domain |
For two households in one domain, with weights 10 and 30 and values 2 and 6: total is 10·2 + 30·6 = 200, and mean is 200 / 40 = 5 (not the plain mean 4, nor the mean of w·y, 100).
Tools: a column made with assign (w·y); groupby(by, as_index=False).agg(...) with "size" and "sum"; a division of two columns. No missing values in y.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
mean is 4.0 for domain A of the small table, not 5.0 |
The plain mean of y, without the weights. |
step 3: Σ w·y ÷ Σ w |
mean is 100.0 for domain A |
The mean of w·y: the total divided by the number of households, not by the sum of their weights. | step 3: divide by the sum of the weights |
total equals the sum of y |
The weights are not used. | step 1: frame[weight] * frame[y] |
| The third case is red and the others green | The weight's name is typed in as "sel_final_weight" instead of taken from weight. |
frame[weight] |
| KeyError: 'domain' or a missing domain column | The column is named "by", or as_index=False is missing and the domain is in the index. |
groupby(by, as_index=False); return [by, "households", "total", "mean"] |
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 weighted total is Σ w·y and a weighted mean is Σ w·y ÷ Σ w, both over the households of one domain. Two sums per group, then one division.
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 weighted_by_domain(frame: pd.DataFrame, y: str, by: str, weight: str = "sel_final_weight") -> pd.DataFrame: """One row per domain: the number of households, the weighted total of y and its weighted mean.""" # Exercise P1.2: the task and examples are in the text above this cell. sums = frame.assign(wy=frame[weight] * frame[y]).groupby(by, as_index=False).agg( households=(weight, "size"), total=("wy", "sum"), weights=(weight, "sum"), ) sums["mean"] = sums["total"] / sums["weights"] return sums[[by, "households", "total", "mean"]]Why each part is there
wyholds each household's value times its weight: the number of household members it stands for in the population.- One
groupbygives the three sums of each domain at once: the rows ("size"), Σ w·y and Σ w. This issvybywithout the variance. - The mean divides the domain's two sums. Taking
meanofywould ignore the weights; takingmeanofwydivides by the number of households instead of the number they stand for. - The result has the domain as a column, then
households,totalandmean, as svy's table has the domain besideest.
Exercise P1.3. A household code into its area codes
The task
Why it matters: the survey's hh_code is the area codes and a serial number written one after another: two digits of region, three of province, two of city or municipality, three of barangay, then three for the household's number in its barangay. An R script splits it with substr, counting from 1 and including both ends. Translated one for one, every part comes out shifted by one character, with no error.
Input → output: a column of household codes (text) → a table with the same row labels and five text columns, region_code, province_code, citymun_code, barangay_code and serial, the zeros kept. A missing household code gives five missing parts.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
"1" for the region and "33" for the province |
R's starts kept: [1:2], [3:5]. |
step 1: subtract 1 from each start only |
"01", then "0331" for the province |
R's ends moved down too, or each end raised by one. | step 1: the end stays as in R |
1 and 33, numbers |
The parts turned into numbers. | keep them as text: no astype(int) |
| AttributeError: Can only use .str accessor with string values | A single household code was passed, or a column of numbers. | the function takes the whole column, as text |
| Row labels 0, 1, 2 for the second case | The parts were made into lists (.tolist()) or the index reset. |
keep each .str[...] result as a column |
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
R's substr(x, a, b) counts from 1 and includes b; Python's x[a - 1:b] counts from 0 and excludes its end. So each start goes down by one and each end stays.
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 hh_code_parts(hh_codes: pd.Series) -> pd.DataFrame: """The area codes and serial number in each household code, as text: region_code, province_code, citymun_code, barangay_code, serial.""" # Exercise P1.3: the task and examples are in the text above this cell. return pd.DataFrame({ "region_code": hh_codes.str[0:2], "province_code": hh_codes.str[2:5], "citymun_code": hh_codes.str[5:7], "barangay_code": hh_codes.str[7:10], "serial": hh_codes.str[10:13], })Why each part is there
- The region is the first two characters:
[0:2], R'ssubstr(x, 1, 2). Writing[1:2]keeps one character, the second. - Each next part starts where the one before ended, which a slice makes easy to see:
[0:2],[2:5],[5:7],[7:10],[10:13]. The end of one is the start of the next. .str[...]slices every value of the column at once, and gives a missing value for a missing household code, so no row is lost or shifted.- The parts stay text:
"01"and"033"keep their zeros, as module 2 keeps every code.int("033")would be 33. pd.DataFrame({...})lines the five columns up by their row labels, which come fromhh_codes, so each row still belongs to its household.