Skip to content
Learn Python with BNHR

Get the tables: from regional databases to one flat table

On this page
  1. Overview
  2. 2.1 · What a regional database holds
  3. 2.2 · Every region's rows of one table
  4. 2.3 · Fishing units still in the survey, every region
  5. 2.4 · Area codes as zero-padded text
  6. 2.5 · Read a table of the export as the database holds it
  7. 2.6 · Types from the codebook
  8. 2.7 · The flat table
  9. 2.8 · Save the flat table, checked

Every exercise in 10_flat_table.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 2.1. What a regional database holds

The task

Why it matters: before reading a region, count what is in it. A table with no rows, or with far fewer than the region next door, is a failed export, and a count taken now is what section 4 checks the flat table against.

Input → output: a connection to one regional database → a pandas table with one row per table in the database, sorted by table name, and two columns:

table rows
assistance …
boat …
… …
selection …

rows is the number of rows each table holds, counted with count(*). A table with no rows is listed with 0.

Tools: con.sql("SHOW TABLES").fetchall(), a loop or list comprehension over the names, SELECT count(*) FROM "..." with the name in double quotes, and pd.DataFrame (above).

If the check is red: common causes

what you see the usual cause look at
ParserException: syntax error at or near "-" A name with a hyphen, written without double quotes. f'SELECT count(*) FROM "{name}"'
ResourceInUseException: connection has an unfinished result fetchone() left the rest of a result waiting. .fetchall()[0][0]
Counts that are estimates, not counts estimated_size from duckdb_tables(). count(*)
The right counts in another order Not sorted by table name. .sort_values("table", ignore_index=True)
Columns named 0 and 1, or name The columns were not named table and rows. pd.DataFrame({"table": ..., "rows": ...})

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 2.2. Every region's rows of one table

The task

Why it matters: this is the R loop in one query. Every table under the household goes through it: units, members, boats, catch. If the region is not on every row, the next join cannot tell region 01's household from region 04's with the same id.

Input → output: a connection with regional databases attached, a table's name, and a list of the attached databases' names (such as ["sfh2025_r01", "sfh2025_r04"]) → a pandas table of that table's rows from every listed database, stacked by name, with a first column region_code: the region's two digits as text ("01"), the last two characters of the database's name. Every other column as the databases store it.

region_code row_id hh_id …
01 1 … …
… … … …
04 1 … …

It is for every table but household, which has its own region_code (section 3 deals with it). The check compares rows in any order.

Tools: a list comprehension over the databases, db[-2:], '01' AS region_code, " UNION ALL BY NAME ".join(...), double quotes around the table's name, and .df(), above.

If the check is red: common causes

what you see the usual cause look at
No region_code column, or region_code reads 1 The region was not added, or added as a number. '01' AS region_code, in single quotes
region_code reads sfh2025_r01 The database's name, not its digits. db[-2:]
Only the small regions' check is red UNION ALL by position: sfh2025_r13's columns are in another order. UNION ALL BY NAME
Fewer rows than the tables hold UNION without ALL dropped rows that repeat. UNION ALL BY NAME
CatalogException: Table with name ... does not exist The table named without its database, or with its name misspelt. {db}."{table}"

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 2.3. Fishing units still in the survey, every region

The task

Why it matters: these are the units the survey counts. Filtered against one list for all regions, the removed households of one region come back in under another region's ids, and every total built on them counts households that are not in the survey.

Input → output: a connection with regional databases attached, and a list of their names → a pandas table of every listed region's rows of fishing_unit that are still in the survey, with region_code (the region's digits, as text) first and then every column of the units table. A unit is still in the survey when, in its own region:

table condition
household its household's hh_deleted_on is blank and its row_void is not 1
selection its household's sel_excluded is not 1
fishing_unit its own row_void is not 1

In the check's small regions, household 101 is deleted in sfh2025_r03 and still in the survey in sfh2025_r13. The check compares rows in any order.

Tools: Exercise 2.2's query, with a WHERE in each region's SELECT: IN with a subquery, IS NULL, IS DISTINCT FROM, and AS u (above).

If the check is red: common causes

what you see the usual cause look at
No rows at all row_void <> 1, sel_excluded <> 1 or hh_deleted_on = NULL: a blank makes the condition NULL. IS DISTINCT FROM 1, and IS NULL for the date
sfh2025_r03's household 101 is still there The kept ids were collected across every region, then used for all. each subquery reads {db}'s own tables
sfh2025_r13's household 102 is still there The household's row_void was not checked. the subquery on household
sfh2025_r03's household 103 is still there The selection's sel_excluded was not checked. the subquery on selection
sfh2025_r03's household 104 is still there The unit's own row_void was not checked. u.row_void IS DISTINCT FROM 1
BinderException: Ambiguous reference to column name "row_void" Two joined tables with row_void in one SELECT, the column named without its table. u.row_void

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 2.4. Area codes as zero-padded text

The task

Why it matters: every join to the code list, every table by province and every key that includes the region depends on these four columns reading the same in every region. One unpadded region and its households find no province, with no error.

Input → output: a pandas table that has some or all of the area code columns (region_code, province_code, citymun_code, barangay_code), stored as integers, as decimals with missing values, or as text with or without zeros → the same table, every other column unchanged, each area code column as text zero-padded to its width in AREA_CODE_WIDTH, a missing code still missing:

column arrives as becomes
region_code 1.0, NaN "01", missing
province_code "33", "010" "033", "010"
citymun_code 1 "01"
barangay_code 19 "019"

Tools: a loop over AREA_CODE_WIDTH.items(), column in table.columns, pd.to_numeric, .astype("Int64").astype("string").str.zfill(width), above. Work on table.copy().

If the check is red: common causes

what you see the usual cause look at
"1.0" in region_code Decimals turned into text without Int64 first. .astype("Int64") before .astype("string")
"nan" or "<NA>" as a code A missing value turned into text. Int64, then "string", keeps it missing
KeyError: 'region_code' A code column the table does not have. if column in out.columns
"33" in province_code zfill with the wrong width, or none. zfill(width) from AREA_CODE_WIDTH

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 2.5. Read a table of the export as the database holds it

The task

Why it matters: a table read from the export should be the table in the database: the same codes, the same missing values, the same text. Then any check on one holds for the other, and a region that sends files instead of database access is processed the same way.

Input → output: the path of one table's CSV in the export (any table, any region) → a pandas table where

column in the file in your table
hh_code and the area codes it has 1, 33, 010 text, zero-padded to its width ("01", "033", "010"); hh_code as written
a whole-number column with \N \N, 1 whole numbers, missing for \N (not decimals, not text)
a text answer Santo Niño wharf and spaces, or nothing "Santo Niño wharf"; an empty answer stays an empty text (''), not missing
anything else as dtype_backend="numpy_nullable" reads it (hh_interview_date stays text)

Tools: pd.read_csv with encoding=, na_values=, keep_default_na=, dtype= and dtype_backend=; then .str.zfill() for the codes and .str.rstrip() for text, above. A dtype= entry for a column the file does not have is ignored, so one dictionary serves every table. You may call your pad_codes from Exercise 2.4.

If the check is red: common causes

what you see the usual cause look at
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 The file read as UTF-8. encoding="cp1252"
row_void holds the text \N \N is not named as missing. na_values=[r"\N"]
row_void is decimals (1.0) \N read as missing, but into a decimal column. dtype_backend="numpy_nullable"
hh_code is a number, or province_code reads 10 Codes read as numbers: the zeros are gone before you can pad them. dtype={"hh_code": str, ...}
province_code reads 33 in region 01 The export never wrote the zeros. .str.zfill(width)
Only the small file's check is red keep_default_na left on: the empty name became missing. keep_default_na=False
Landing names end in spaces The padding is still there. .str.rstrip() on text columns

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 2.6. Types from the codebook

The task

Why it matters: a table whose types depend on its rows breaks the day a batch has no missing value in a column, or no value at all. Typed from the codebook, every region and every batch reads the same, whichever reader brought it in.

Input → output: a pandas table, the codebook (the table above, every table's rows), and the survey table's name → the same table, each column the codebook lists for that table typed by its codebook type:

codebook type pandas type why
INTEGER a nullable integer: "Int64" whole, and able to hold a missing value, missing or not
DOUBLE decimals: "Float64" (or float64) even when every value happens to be whole
VARCHAR text: "string"
DATE as it comes

Leave alone the area codes (AREA_CODE_WIDTH: Exercise 2.4 types them) and any column the codebook does not list for that table. A column typed INTEGER whose values are all missing still becomes Int64.

Tools: a filter on the codebook (codebook["table"] == name), a dictionary from variable to type, a loop over the table's columns, and .astype(...).

If the check is red: common causes

what you see the usual cause look at
IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer "int64", which has no missing value. "Int64", capital I
row_void is not whole numbers Only the columns with values were typed, or the type was guessed from the values. type every listed column from the codebook
sel_design_weight is whole numbers The type was inferred from the values (1, 3, 15). DOUBLE is decimals, whatever the values
province_code is whole numbers The area codes were typed INTEGER too. column not in AREA_CODE_WIDTH
KeyError: 'checked_by' A column the codebook does not list. if column in types
A column typed by another table's row The codebook was not filtered to this table. codebook["table"] == 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.

Exercise 2.7. The flat table

The task

Why it matters: modules 5 and 6 tabulate and estimate from this table. A row too many is a unit counted twice in every weighted total; a code left unpadded is a province missing from every table by province.

Input → output: a connection with regional databases attached, and a list of their names → a pandas table with one row per fishing unit still in the survey (Exercise 2.3's rows), and these columns, the names in FLAT_COLUMNS:

If the check is red: common causes

what you see the usual cause look at
Many more rows than units The regions were stacked first and joined on hh_id alone. the joins inside each region's SELECT
province_code reads 33 or 12 The codes of regions 01 and 07 were not padded. lpad(CAST(h.province_code AS VARCHAR), 3, '0')
No rows A mark tested with <> 1, or the date with = NULL. IS DISTINCT FROM 1, IS NULL
Removed households still there One of the four marks is not tested. h.hh_deleted_on, h.row_void, s.sel_excluded, u.row_void
BinderException: Ambiguous reference to column name A column two joined tables share (hh_id, row_void), named without its table. u.hh_id, h.row_void
A column missing or misnamed The SELECT list differs from FLAT_COLUMNS. AS province_code after each lpad

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 2.8. Save the flat table, checked

The task

Why it matters: the flat table is handed to the tabulation, maybe on another day or to another person. A file that says it holds the survey's fishing units must hold exactly them; a refusal now costs a minute, a wrong file found in the published tables costs a correction.

Input → output: a table, a path ending in .parquet, and the number of rows it should have → the number of rows in the written file, read back from the file. If the table does not have the expected number of rows, write nothing and raise a ValueError with exactly this message (numbers with thousands separators):

the flat table has 1,240 rows, but 1,234 were expected: nothing was written
table's rows expected result
1,234 1,234 the file is written; 1234, read back
1,240 1,234 ValueError, as above; no file

Tools: len(table), raise ValueError(f"...") with {n:,} for the separators, to_parquet(path, index=False), and pl.scan_parquet(path).select(pl.len()).collect().item(), above.

If the check is red: common causes

what you see the usual cause look at
ValueError: the flat table has 3 rows, but 4 were expected... is red The message differs by a word, a comma or a space. copy the message from the text, with {n:,}
1240 rows without a comma The numbers were written without their separators. {len(table):,}
A number where a ValueError was expected The count is not checked, or checked after writing. if len(table) != expected: raise ... first
AttributeError: 'LazyFrame' object has no attribute 'item' The query was not run. .collect().item()
One more column when the file is read back The index was written. index=False

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 module
ModulePublish the tables
AboutModule 7 of Python for Survey Statistics: estimates written to a formatted workbook, and the tabulation as one script that writes every table at every level, with the sample's own counts beside each estimate, to one workbook. Its sections, its notebooks to read on the web, and the companion's solutions and explanations.
CoursePython for Survey Statistics, free