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.
The idea
List the tables, then count each one's rows with its own query, the name in double quotes so that any name works.
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 table_counts(con: duckdb.DuckDBPyConnection) -> pd.DataFrame: """One row per table of the connection's database: table and rows, sorted by table name.""" # Exercise 2.1: the task and examples are in the text above this cell. names = [row[0] for row in con.sql("SHOW TABLES").fetchall()] rows = [con.sql(f'SELECT count(*) FROM "{name}"').fetchall()[0][0] for name in names] return pd.DataFrame({"table": names, "rows": rows}).sort_values("table", ignore_index=True)Why each part is there
SHOW TABLESlists the tables of the connection's current database: for a connection to one file, that file's tables. Each row is a tuple of one name, hencerow[0].f'SELECT count(*) FROM "{name}"'puts the name in double quotes. The survey's names do not need them, but the check's small database has a table namedhousehold-backup, which without them reads ashouseholdminusbackup, and DuckDB stops with a parser error.count(*)counts the rows.duckdb_tables()has anestimated_sizecolumn, but it is an estimate, and on a MySQL table attached through DuckDB (section 5) it reads 0.fetchall()[0][0]takes every row of the result (one row, one value) and leaves nothing waiting on the connection;fetchone()would leave the result open and refuse the next count.
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.
The idea
One SELECT per region, each stamping its rows with the region taken from the database's name, stacked by column name in one query.
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 stack_regions(con: duckdb.DuckDBPyConnection, table: str, databases: list[str]) -> pd.DataFrame: """Every listed database's rows of one table, stacked by name, with region_code (the region's two digits, as text) first.""" # Exercise 2.2: the task and examples are in the text above this cell. parts = [f"""SELECT '{db[-2:]}' AS region_code, * FROM {db}."{table}\"""" for db in databases] return con.sql(" UNION ALL BY NAME ".join(parts)).df()Why each part is there
'{db[-2:]}' AS region_codewrites the region on every row as text,'01'with its zero. Without it, rows of two regions with the same household id cannot be told apart.{db}."{table}"names the table in its database, the table's name in double quotes, as in Exercise 2.1.UNION ALL BY NAMElines columns up by name: a region whose table has its columns in another order still stacks right. PlainUNION ALLwould put one column's values under another's name, with no error.ALLkeeps every row; plainUNIONwould drop rows that are equal in every column, and duplicates are for the edit rules to find.
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.
The idea
Filter each region's units against that region's own households and selection rows, inside its own SELECT, then stack the regions by name.
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 live_units(con: duckdb.DuckDBPyConnection, databases: list[str]) -> pd.DataFrame: """Every listed region's fishing units still in the survey, filtered region by region, with region_code (text) first.""" # Exercise 2.3: the task and examples are in the text above this cell. parts = [] for db in databases: parts.append(f""" SELECT '{db[-2:]}' AS region_code, u.* FROM {db}.fishing_unit AS u WHERE u.row_void IS DISTINCT FROM 1 AND u.hh_id IN (SELECT hh_id FROM {db}.household WHERE hh_deleted_on IS NULL AND row_void IS DISTINCT FROM 1) AND u.hh_id IN (SELECT hh_id FROM {db}.selection WHERE sel_excluded IS DISTINCT FROM 1)""") return con.sql(" UNION ALL BY NAME ".join(parts)).df()Why each part is there
- The subqueries read
{db}.householdand{db}.selection, the same region's tables: an id removed in this region cannot be rescued by another region's household of the same number. IS DISTINCT FROM 1keeps blank marks. With<> 1, a blankrow_voidorsel_excludedmakes the conditionNULL, and the query keeps nothing.hh_deleted_on IS NULLtests the date for a blank.hh_deleted_on = NULLisNULLon every row, and keeps nothing.u.row_voidis the unit's own mark: a unit can be voided in a household that stays.- The selection condition is written as "in the households not excluded" rather than
NOT IN (the excluded ones):NOT INagainst a subquery that returns aNULLis never true, and keeps no row at all. UNION ALL BY NAMEstacks the regions by column name, withregion_codefirst, as in Exercise 2.2.
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.
The idea
Bring every code to one form first, a nullable whole number, then write it as text padded with zeros to its width.
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 pad_codes(table: pd.DataFrame) -> pd.DataFrame: """The table with each area code column it has as text, zero-padded to its width in AREA_CODE_WIDTH; missing stays missing.""" # Exercise 2.4: the task and examples are in the text above this cell. out = table.copy() for column, width in AREA_CODE_WIDTH.items(): if column in out.columns: out[column] = pd.to_numeric(out[column]).astype("Int64").astype("string").str.zfill(width) return outWhy each part is there
pd.to_numericreads integers, decimals and text alike as numbers, so a code that arrives as"010",10or10.0goes the same way from here..astype("Int64")drops the decimal point that a missing value forced on the column, and keeps the missing value missing..astype(str)on decimals would give"33.0", whichzfill(3)leaves as it is..astype("string").str.zfill(width)pads on the left to the column's width, fromAREA_CODE_WIDTH, so the widths are written once, incourse.py.if column in out.columnsskips the codes a table does not have:memberhas none of the four, andlandingnames its province and city codesland_province_codeandland_citymun_code.
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.
The idea
Tell the reader the export's three habits (its encoding, its missing marker, and which columns are codes), then undo the padding the export adds and put back the zeros it left out.
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 read_export(path: Path) -> pd.DataFrame: """One table of the CSV export: Windows-1252, only \\N missing, codes as zero-padded text, whole numbers whole, text unpadded.""" # Exercise 2.5: the task and examples are in the text above this cell. codes = ["hh_code", *AREA_CODE_WIDTH] table = pd.read_csv(path, encoding="cp1252", na_values=[r"\N"], keep_default_na=False, dtype={column: str for column in codes}, dtype_backend="numpy_nullable") for column, width in AREA_CODE_WIDTH.items(): if column in table.columns: table[column] = table[column].str.zfill(width) for column in table.columns: if pd.api.types.is_string_dtype(table[column]): table[column] = table[column].str.rstrip() return tableWhy each part is there
encoding="cp1252": the export writesñas one byte, which the UTF-8 default refuses."latin-1"reads this export the same, for the reason the cell before DuckDB's reader counts.na_values=[r"\N"], keep_default_na=False:\Nis the database'sNULL, and the only one. With the defaults on, an empty text answer would also become missing, and the table would no longer match the database.dtype=with the codes asstrkeeps region 04's zeros andhh_code's;dtype_backend="numpy_nullable"gives every other whole-number column theInt64type, which holds a missing value and stays whole..str.zfill(width)puts back the zeros regions 01 and 07 never wrote: their export has33where the code is033..str.rstrip()removes only the spaces at the end, the export's padding..str.strip()would also remove spaces at the start, which an answer may really have.
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.
The idea
The codebook says what each variable is; type the columns from that, so the types do not depend on which rows happened to come back.
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 restore_types(table: pd.DataFrame, codebook: pd.DataFrame, name: str) -> pd.DataFrame: """The table with each column the codebook lists for the survey table `name` typed by its codebook type (INTEGER as Int64, DOUBLE as Float64, VARCHAR as string); area codes, DATE columns and unlisted columns left as they come.""" # Exercise 2.6: the task and examples are in the text above this cell. types = dict(zip(*codebook.loc[codebook["table"] == name, ["variable", "type"]].to_numpy().T)) pandas_type = {"INTEGER": "Int64", "DOUBLE": "Float64", "VARCHAR": "string"} out = table.copy() for column in out.columns: if column in types and column not in AREA_CODE_WIDTH and types[column] in pandas_type: out[column] = out[column].astype(pandas_type[types[column]]) return outWhy each part is there
codebook[codebook["table"] == name]keeps the variables of this table only:row_void,row_idandhh_idare listed in all ten tables."Int64"forINTEGER: decimals fromread_sqlbecome whole again, a column with no missing value gets the same type as one with many, and an all-missing column (anobjectcolumn ofNone) becomes a whole-number column of missing values..astype("int64")would stop at the first missing value with IntCastingNaNError."Float64"forDOUBLE, even when every value is whole: inferring from the values would make a weight of 5.0 an integer, and the next batch's 5.25 would not fit.- The area codes are skipped: the codebook types them
INTEGERbecause two regions store them so, but a code is text (Exercise 2.4).
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.
The idea
Join each region's units to that region's households and selection rows, where a household id is unique, filter the removals there, pad the codes there, and stack the regions.
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 flat_table(con: duckdb.DuckDBPyConnection, databases: list[str]) -> pd.DataFrame: """One row per fishing unit still in the survey, every listed region: the household's area codes as padded text, the unit's key and answers, and its household's stratum, area and final weight (FLAT_COLUMNS).""" # Exercise 2.7: the task and examples are in the text above this cell. area = ", ".join(f"lpad(CAST(h.{column} AS VARCHAR), {width}, '0') AS {column}" for column, width in AREA_CODE_WIDTH.items()) unit = ", ".join(f"u.{column}" for column in UNIT_COLUMNS) design = ", ".join(f"s.{column}" for column in DESIGN_COLUMNS) parts = [] for db in databases: parts.append(f""" SELECT {area}, {unit}, {design} FROM {db}.fishing_unit AS u JOIN {db}.household AS h ON h.hh_id = u.hh_id JOIN {db}.selection AS s ON s.hh_id = u.hh_id WHERE h.hh_deleted_on IS NULL AND h.row_void IS DISTINCT FROM 1 AND s.sel_excluded IS DISTINCT FROM 1 AND u.row_void IS DISTINCT FROM 1""") return con.sql(" UNION ALL BY NAME ".join(parts)).df()Why each part is there
- The joins are inside each region's
SELECT: joined after stacking onhh_idalone, each unit would also match the household of the same number in every other region. lpad(CAST(h.province_code AS VARCHAR), 3, '0')gives every region the same text: region 04's'010'is unchanged, region 01's33becomes'033'. Without it, the stack mixes'33'and'010'.- The marks are tested with
IS NULLandIS DISTINCT FROM 1, as in Exercise 2.3: a blank mark is not a removal. - Inner joins drop a unit with no household or no selection row. Every unit of the survey has both, and the row-count check below is what would show it if one did not.
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.
The idea
Check the count before writing, so a wrong table never reaches the disk, and count again from the file, so what was written is proved, not assumed.
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 save_flat(table: pd.DataFrame, path: Path, expected: int) -> int: """Write the table to Parquet only if it has the expected number of rows; return the rows read back from the file.""" # Exercise 2.8: the task and examples are in the text above this cell. if len(table) != expected: raise ValueError(f"the flat table has {len(table):,} rows, but {expected:,} were expected: nothing was written") table.to_parquet(path, index=False) return pl.scan_parquet(path).select(pl.len()).collect().item()Why each part is there
- The check comes first: raising after
to_parquetwould leave a wrong file on disk for someone to pick up. {len(table):,}writes 1,240 with its separator, as the message asks; the message says what was found, what was expected and what happened, so whoever reads it knows what to do next.index=False: the row numbers are not data, and written, they come back as an extra column.pl.scan_parquet(path).select(pl.len())reads the count from the file's footer. Returninglen(table)would report what you meant to write; reading back reports what is there.