Skip to content
Learn Python with BNHR

Debugging drill: a flat table that lies

On this page
  1. Overview
  2. D1.1 · A code that loses its leading zero
  3. D1.2 · A join that multiplied rows
  4. D1.3 · A removal filter that keeps everything
  5. D1.4 · The null token read as text
  6. D1.5 · A key part compared as a number against text
  7. D1.6 · A region's file attached twice

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.

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.

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.

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.

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.

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.

Something new

Identify results
LayerDid you know?
TopicPython
FactPython is named after the BBC comedy series Monty Python's Flying Circus, not the snake. Its creator, Guido van Rossum, wanted a name that was short, unique and slightly mysterious.
SourceGeneral Python FAQ: Why is it called Python? (Python documentation) (opens in a new tab) ↗
LinkShare this fact