Every exercise in 35_debugging_drill.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.
Drill D1.1. A code that loses its leading zero
The task
Why it matters: hh_code is how a household is found in the listing, and its first seven digits are its city or municipality's place in the PSGC (the barangay's three digits after them are the course's own numbering). A code that loses a digit matches nothing, without an error.
hh_code is 13 digits of text: the region (2), province (3), city or municipality (2) and barangay (3) codes, then the household's number in its barangay (3). Region 04's first household is 0401028032001. with_psgc(path) should read a region's household.csv from the export, keep hh_code as that 13-digit text, and add psgc, the 10-digit PSGC code of the household's city or municipality: the first seven digits of hh_code, then 000.
Input → output: the path of a region's household.csv → its households, with hh_code as text and a psgc column.
| call | should give |
|---|---|
with_psgc(HOUSEHOLD_CSV["04"])["psgc"].head(3).tolist() |
['0401028000', '0401028000', '0401007000'] |
with_psgc(HOUSEHOLD_CSV["04"])["psgc"].isin(geography["psgc"]).sum() |
736: every household's city or municipality is in the code list |
Tools: codes kept whole (module 2, section 3 (10_flat_table.py)).
Predict. What will the function give as the first household's psgc?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
hh_code has 12 digits, psgc starts with 4 |
The column is still read as numbers. | read_csv's dtype= for hh_code |
psgc is right, but hh_code still has 12 digits |
The zero was put back in psgc only. The task keeps hh_code itself as 13-digit text. |
where hh_code is read |
| AttributeError: Can only use .str accessor with string values | .astype(str) was removed while hh_code is still a number. |
read hh_code as text from the start |
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
What was wrong: read_csv saw a column of digits and read it as whole numbers, and a number has no leading zero, so 0401028032001 became 401028032001. The PSGC code was then cut from the wrong digits: 4010280000 instead of 0401028000.
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 with_psgc(path) -> pd.DataFrame: """A region's households from the export, hh_code as 13-digit text, each with its city or municipality's PSGC code.""" # Drill D1.1: the task is in the text above this cell. Find the mistake and fix it. table = pd.read_csv(path, encoding="cp1252", dtype={"hh_code": str}) table["psgc"] = table["hh_code"].astype(str).str[:7] + "000" return tableWhy each part is there
dtype={"hh_code": str}tellsread_csvto keep the column as text, exactly as the export writes it, so all 13 digits stay.- The
.astype(str)on the next line was someone's answer to an earlier error:.strworks only on text, and pandas refused it on numbers. Turning the numbers into text came too late, after the zero was gone, so it turned an error into a wrong answer. - Every region of this survey starts with 0, so every household was hurt; a region such as 11 (Davao Region) would have come out right, which is why the check also tries a small file with a household of each kind.
- Putting the zero back with
.str.zfill(13)gives the same codes here, because everyhh_codehas 13 digits. Reading the column as text is still the safer habit: it does not depend on knowing the width, and the R way does the same with readr'scol_types =.
Drill D1.2. A join that multiplied rows
The task
Why it matters: the flat table carries each household's weight, and every total is a sum of weights. A join that repeats a household counts it two or three times, and nothing about the table looks wrong.
with_weight(households, selection) should give every household its final weight, sel_final_weight, from the selection table: one row per household, in the order of households.
Input → output: the households and the selection table → the households, each with sel_final_weight.
| call | should give |
|---|---|
len(with_weight(households, selection)) |
2180: as many rows as households |
round(with_weight(households, selection)["sel_final_weight"].sum()) |
22485: the weighted number of fishing households in the three regions |
Tools: the survey's keys (module 1, section 2 (00_start.py)), keys of several parts (module 3, section 3 (20_key_matching.py)).
Predict. households has 2,180 rows. How many will the joined table have?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
More rows than households, weights summing to far more |
The join is on hh_id alone, which repeats across regions. |
on= with both key parts |
| KeyError: 'region_code' | on= names region_code, but the columns taken from selection don't include it. |
the list of selection's columns |
Columns region_code_x and region_code_y |
region_code came from both tables but is not in on=. |
on= |
| MergeError: ... not a one-to-one merge | validate= found a key that repeats: the join is still on part of the key. |
on= |
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
What was wrong: hh_id is unique only within its region's database: regions 01, 04 and 07 each number their households from the 5000s, so the same id is a household in two or three regions. Joined on the id alone, each household met every selection record with its number in any region, and took a weight for each. A household is its region and its id together.
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 with_weight(households: pd.DataFrame, selection: pd.DataFrame) -> pd.DataFrame: """Every household with its final weight, sel_final_weight: one row per household.""" # Drill D1.2: the task is in the text above this cell. Find the mistake and fix it. return households.merge(selection[["region_code", "hh_id", "sel_final_weight"]], on=["region_code", "hh_id"], how="left", validate="one_to_one")Why each part is there
on=["region_code", "hh_id"]joins on the whole key, so a household meets only its own selection record;region_codecomes along from the selection table for that.validate="one_to_one"writes down what the join should be: one selection record for each household, and one household for each record. pandas checks it and stops with aMergeErrorif it is not, so a key that is not unique becomes an error instead of a total two or three times too large.- The R way has the same guard: dplyr warns about an unexpected many-to-many relationship, and
relationship = "one-to-one"is itsvalidate=.
Drill D1.3. A removal filter that keeps everything
The task
Why it matters: a removed household should not be in the survey's tables at all: a household interviewed twice, one out of scope, an interview withdrawn. Left in, it is counted with its weight like any other.
The household table marks a removed household in two ways: hh_deleted_on holds the day it was deleted in the capture system (blank if it never was), and row_void = 1 says it was voided in editing (blank otherwise). without_removed(households) should give back the households that are marked neither way. (A third mark, sel_excluded in the selection table, belongs to the sampling side; course.table() leaves out all three, as module 2 does.)
Input → output: a household table → the same rows, without any household removed either way.
| call | should give |
|---|---|
len(without_removed(households_with_removed)) |
2186 |
without_removed(households_with_removed)["hh_deleted_on"].notna().sum() |
0: no household deleted in the capture system is left |
Tools: deleted rows filtered (module 2, section 2 (10_flat_table.py)).
Predict. Read the function's filter aloud. Which households does it keep?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| Every row comes back | ~deleted | ~voided: each household is missing one mark or the other. |
~(deleted | voided), or & between the two ~ |
| Only the removed households come back | The ~ was dropped: the filter now picks the households to leave out. |
negate the condition |
| No household comes back, and no error | .fillna(False) was removed: a blank row_void gives <NA> instead of False, and a filter keeps no row whose condition is <NA>. |
keep the line that builds voided |
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
What was wrong: "not deleted or not voided" is true of every household that is missing either mark, and every removed household in this survey carries only one of the two. So the filter kept all 2,195 households, the removed ones too. A household to keep is removed neither way: "not (deleted or voided)", which is "not deleted and not voided".
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 without_removed(households: pd.DataFrame) -> pd.DataFrame: """The households neither deleted in the capture system nor voided in editing.""" deleted = households["hh_deleted_on"].notna() # deleted in the capture system: the day is filled in voided = households["row_void"].eq(1).fillna(False) # voided in editing; a blank row_void is not voided # Drill D1.3: the task is in the text above this cell. Find the mistake and fix it. return households[~(deleted | voided)]Why each part is there
~(deleted | voided)says it the way the rule is written: first the households to leave out, then all the others.~deleted & ~voidedis the same filter. Taking a~inside the brackets turns|into&: this is De Morgan's law, and getting it half right is the classic way a filter keeps what it should drop.- Nothing raised an error, and the count was off by only 9 of 2,195. A count of what is left out, beside the count of what is kept, is the check that finds it.
Drill D1.4. The null token read as text
The task
Why it matters: a boat's gross tonnage decides whether its fishing unit is small-scale or large-scale, split at 5.0 gross tons. It is computed from the boat's dimensions, and in the export a dimension that was not measured is not blank: it is \N.
The database export writes every missing value as \N, the null token. A boat's size comes from its registration papers (boat_measured_in = 1), or it was measured in meters (2) or in feet (3); boat_length, boat_beam and boat_depth hold the dimensions in that unit, and \N for a boat sized from its papers. boats_with_tonnage(path) should read a region's boat.csv and add gt, the gross tonnage from the dimensions as the survey's manual sets it (the codebook's rule B3): length × beam × depth × 0.212 in meters, or × 0.006 in feet, and missing for a boat sized from its papers.
Input → output: the path of a region's boats file → its boats, with gt.
| call | should give |
|---|---|
boats_with_tonnage(BOAT_CSV["01"])["gt"].round(2).head(3).tolist() |
[nan, 47.66, 3.15]: the first boat is sized from its papers |
boats_with_tonnage(BOAT_CSV["01"])["gt"].notna().sum() |
807: every boat measured in meters or in feet |
Tools: null tokens (module 2, section 3 (10_flat_table.py)).
Predict. Will the function run? If it stops, on which line?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| TypeError: Can only string multiply by an integer | The dimension columns are text, because of \N. |
read_csv's na_values= |
| ValueError: could not convert string to float: '\N' | .astype(float) on a column that still holds \N. |
read \N as missing in the first place |
| SyntaxError: (unicode error) ... malformed \N character escape | "\N" without the r: in a normal string, \N starts a named character. |
r"\N", or "\\N" |
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
What was wrong: read_csv knows several ways of writing a missing value (an empty field, NA, NULL), but not \N. Each dimension column holds \N for the boats sized from their papers, so pandas read each one as text, and multiplying text by text stopped with TypeError: Can only string multiply by an integer.
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 boats_with_tonnage(path) -> pd.DataFrame: """A region's boats from the export, each with its gross tonnage computed from its dimensions.""" # Drill D1.4: the task is in the text above this cell. Find the mistake and fix it. boats = pd.read_csv(path, encoding="cp1252", na_values=[r"\N"]) factor = boats["boat_measured_in"].map({2: 0.212, 3: 0.006}) # gross tons per cubic meter, per cubic foot boats["gt"] = boats["boat_length"] * boats["boat_beam"] * boats["boat_depth"] * factor return boatsWhy each part is there
na_values=[r"\N"]adds the export's null token to the valuesread_csvreads as missing. The dimension columns then hold numbers andNaN, and their type isfloat64.- The
rbefore the quotes keeps the backslash as a backslash:r"\N"is the two characters the export writes. - With
NaNfor a boat sized from its papers, the product isNaNtoo, and so is its factor:mapgivesNaNfor the code 1, which the mapping leaves out. pd.to_numeric(column, errors="coerce")on each column after reading also gives the right numbers, by turning anything that is not a number intoNaN. It would hide a typo such as7,5the same way, which is why naming the token is the safer fix. The R way names it too:na = c("", "NA", "\\N")in readr.
Drill D1.5. A key part compared as a number against text
The task
Why it matters: a published table names places, not codes. The names come from the PSGC code list, joined on the area codes, and a region whose codes are stored another way gets no names, or stops the pipeline.
The regional databases do not agree on how they store area codes: regions 01 and 07 store region_code, province_code and citymun_code as numbers (1, 33, 10), region 04 as zero-padded text ('04', '010', '28'). The code list geography has them as zero-padded text. with_citymun(households) should take one region's households as its database stores them and give each household's city or municipality name.
Input → output: a region's household table as stored → hh_id and name, one row per household.
| call | should give |
|---|---|
with_citymun(stored["01"])["name"].head(3).tolist() |
['Luna', 'Santo Tomas', 'Rosario'] |
with_citymun(stored["01"])["name"].isna().sum() |
0: every household named |
Tools: text types and zero-padding (module 2, section 3 (10_flat_table.py)).
Predict. The function was written and tried on region 04. What will it do on region 01?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| ValueError: You are trying to merge on int32 and string columns | The codes are numbers in the households and text in the code list. | turn the codes into text before the join |
| Every name missing, no error | .astype(str) without padding ('1' is not '01'), or a column padded to another's width: province_code has 3 digits, the others 2. |
.str.zfill() with each column's own width |
| KeyError: 'name' | The code list's columns were not all taken. | geography[[*keys, "name"]] |
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
What was wrong: a join compares key values, and pandas will not compare the number 1 with the text '01': on region 01 it stopped with ValueError: You are trying to merge on int32 and string columns for key 'region_code'. On region 04, whose codes are text like the code list's, the same code worked, which is why it passed when it was written.
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 with_citymun(households: pd.DataFrame) -> pd.DataFrame: """One region's households, as its database stores them, each with its city or municipality's name.""" keys = ["region_code", "province_code", "citymun_code"] table = households[["hh_id", *keys]].copy() # Drill D1.5: the task is in the text above this cell. Find the mistake and fix it. for column in keys: table[column] = table[column].astype(str).str.zfill(AREA_CODE_WIDTH[column]) named = table.merge(geography[[*keys, "name"]], on=keys, how="left") return named[["hh_id", "name"]]Why each part is there
- The loop turns each code into text and pads it with zeros to its width (2, 3 and 2 digits), the form the code list uses:
1becomes'01',33becomes'033'. On region 04 it changes nothing, so the same function serves every region. .astype(str)alone is not enough:1becomes'1', which is text but not'01'. The join then runs without an error and matches nothing, and every name is missing, a second, silent version of the same bug.course.AREA_CODE_WIDTHholds the widths, as module 2 uses them; the R way pads the same way, withstr_pad(province_code, 3, pad = "0"). Turning the code list's text into numbers instead would also join, but it throws away the form the codes are published in.
Drill D1.6. A region's file attached twice
The task
Why it matters: the flat table is built by stacking every region's database. A region stacked twice doubles its share of every count and every total, and each of its rows is a real row.
households_of_every_region(folder) should attach every regional database in a folder, named sfh2025_r and the region's two digits (sfh2025_r01.duckdb), whichever regions the folder holds, and give every household once: region_code, hh_id and hh_code, sorted by region and id. The setup made two folders as a computer's Downloads folder can look: FOLDER_07_TWICE holds the three regions' databases and region 07's downloaded a second time, which the browser saved as sfh2025_r07 (1).duckdb; FOLDER_04_COPY holds region 04's and a copy, sfh2025_r04 - Copy.duckdb.
Input → output: a folder → one row per household of each region in it.
| call | should give |
|---|---|
households_of_every_region(PATHS.data).groupby("region_code").size().to_dict() |
{'01': 744, '04': 736, '07': 715} |
households_of_every_region(FOLDER_07_TWICE).groupby("region_code").size().to_dict() |
{'01': 744, '04': 736, '07': 715}: the same households |
Tools: every region in one query (module 2, section 2 (10_flat_table.py)), duplicates by key (module 4, section 5 (30_edit_rules.py)).
Predict. Run Try it below, on the course's own data/ folder. Is anything wrong with what it gives?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| One region with twice its households | The file pattern also matches a copy of that region's database. | the pattern in glob |
| IOException about a file that does not exist | The files are named from REGIONS, but the folder holds other regions. |
read the regions the folder holds |
| Right counts on these folders, but the cause still there | Duplicates were dropped after stacking. That works only while the copy is identical to its original. | find each region's file once |
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
What was wrong: the pattern sfh2025_r*.duckdb matches any name that starts with sfh2025_r and ends with .duckdb, so it also found sfh2025_r07 (1).duckdb, the second download. The function attached it as one more database, and region 07's households came in twice. Every row was a real household, so nothing raised an error, and on the course's own folder the answer was right.
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 households_of_every_region(folder) -> pd.DataFrame: """Every household of every regional database in the folder, once, sorted by region and household id.""" # Drill D1.6: the task is in the text above this cell. Find the mistake and fix it. files = sorted(folder.glob("sfh2025_r??.duckdb")) con = duckdb.connect() for k, path in enumerate(files): con.execute(f"ATTACH '{path.as_posix()}' AS db{k} (READ_ONLY)") select = "SELECT lpad(CAST(region_code AS VARCHAR), 2, '0') AS region_code, hh_id, hh_code FROM {db}.household" query = " UNION ALL BY NAME ".join(select.format(db=f"db{k}") for k in range(len(files))) table = con.execute(query + " ORDER BY region_code, hh_id").df() con.close() return tableWhy each part is there
sfh2025_r??.duckdbmatchessfh2025_rfollowed by exactly two characters: one file per region, whatever regions the folder holds, and no copy whose name is longer.- A key check after the stacking is what would have caught it in a real run:
table.duplicated(["region_code", "hh_id"]).sum()should be 0, and a count of households by region should match each database's own count. - Dropping duplicates after stacking gives the same table here, because each copy is identical to its original. An older download of the same region would not be: its changed rows would stay in beside the new ones. Finding each region's file once removes the cause.
- The R way usually lists the databases by name in the script. A copy on disk cannot slip into such a list, but a name typed twice can, so the key check belongs after either way of building the list.