Skip to content
Learn Python with BNHR

Primer: from R to Python

On this page
  1. Overview
  2. P1.1 · Areas and households by province
  3. P1.2 · Weighted totals and means by domain, without svy
  4. P1.3 · A household code into its area codes

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 of hh_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.

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.

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.

Something new

Identify results
LayerExplore a stretch exercises
Stretch exercises S4Stretch: agents for your pipeline, a showcase
AboutStretch S4 of Python for Survey Statistics, after module 9: a showcase of what AI agents, hosted and local, can do for a survey's processing pipeline, with what each sends away and how to limit them.
CoursePython for Survey Statistics, free