Every exercise in 60_publish_tables.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 7.1. Every level in one long table
The task
Why it matters: the workbook, the CSV files and the report all start from one table that holds every level. If a province's row is doubled by the join that names it, every one of its estimates appears twice, and a reader who adds up the provinces gets a total twice too large.
Input → output: the three tables estimate gives for one indicator (national, regional, provincial) and the code list geography → one table with the national row first, then the regions, then the provinces, and these columns. The example is the check's small made-up table:
| level | region_code | province_code | domain | estimate | se | cv | n |
|---|---|---|---|---|---|---|---|
| national | missing | missing | All regions | 300.0 | 30.0 | 0.100 | 40 |
| regional | 01 | missing | Region I (Ilocos Region) | 200.0 | 25.0 | 0.125 | 25 |
| provincial | 01 | 033 | La Union | 120.0 | 18.0 | 0.150 | 15 |
level:"national","regional"or"provincial";domain: the name a reader sees:"All regions"for the national row, the region's name (geography'sregion) for a region, the province's name (province) for a province;region_code,province_code: the codes, missing where the level has none;- one row per row of the three inputs, no more.
Tools: drop_duplicates on the code list's name columns, merge(..., validate="many_to_one"), assign, and pd.concat, all from Arrays & DataFrames and module 3.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| MergeError: Merge keys are not unique in right dataset | The code list still has a row per city or municipality. | drop_duplicates() before the merge |
| Far more rows than the inputs have, each province repeated | The same, without validate=: the join multiplied the rows. |
drop_duplicates(), and validate="many_to_one" to catch it |
Every province named after its region, or no domain column |
The provinces were named from region, or the name column not renamed to domain. |
rename(columns={"province": "domain"}) |
The national row's domain is missing |
Only the regional and provincial tables were named. | national.assign(domain="All regions") |
| KeyError: 'level' | The tables were stacked without a level. | .assign(level=...) on each |
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
Name each level from a list with one row per region or per province, then stack the three tables; the national row has no codes, and concat leaves its code columns missing.
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_levels(national: pd.DataFrame, regional: pd.DataFrame, provincial: pd.DataFrame, geography: pd.DataFrame) -> pd.DataFrame: """The three levels' estimates in one table: level, region_code, province_code, domain (the name a reader sees), estimate, se, cv and n; the national row first, then the regions, then the provinces.""" # Exercise 7.1: the task and examples are in the text above this cell. regions = geography[["region_code", "region"]].drop_duplicates().rename(columns={"region": "domain"}) provinces = geography[["region_code", "province_code", "province"]].drop_duplicates().rename(columns={"province": "domain"}) parts = [ national.assign(level="national", domain="All regions"), regional.merge(regions, on="region_code", how="left", validate="many_to_one").assign(level="regional"), provincial.merge(provinces, on=["region_code", "province_code"], how="left", validate="many_to_one").assign(level="provincial"), ] return pd.concat(parts, ignore_index=True)[["level", "region_code", "province_code", "domain", "estimate", "se", "cv", "n"]]Why each part is there
geographyhas one row per city or municipality, so its province names repeat.drop_duplicates()on the code and name columns leaves one row per province; without it each province would match once per city or municipality and its estimates would be repeated.validate="many_to_one"makes pandas refuse the join if a code still had two names: the check is in the code, not in your memory.how="left"keeps a region or province even if the code list lacks it: its name is then missing, which shows, instead of the row vanishing.pd.concatlines the tables up by column name and fills the columns a table lacks with missing values: the national row gets no codes, the regions no province code.
Exercise 7.2. A sheet with a header, number formats and frozen panes
The task
Why it matters: this is the function every sheet of the workbook is written with, the notes sheet included. Get the formats right once and every table of every batch reads the same.
Input → output: a workbook, a sheet title and a table → the new sheet, added at the end of the workbook, holding:
- row 1: the table's column names, bold;
- one row per table row, the values as they are (a missing value as an empty cell), in the table's columns, no index;
- number formats:
estimateandsein the format of the row's indicator (INDICATORS[indicator][2]:"#,##0"for totals,"0.00"for the mean); every other column named inNUMBER_FORMATS(cvas"0.0%",nas"#,##0") in its format; anything else left as it is ("General"); - the panes frozen below the header (
"A2").
The first rows of the check's small made-up table, as the sheet shows them:
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | domain | indicator | estimate | se | cv | n |
| 2 | La Union | fishing households | 3,812 | 151 | 4.0% | 375 |
| 3 | La Union | mean household size | 4.31 | 0.07 | 1.6% | 375 |
A table without estimate (the notes sheet's item and note) is written the same way, with no number formats.
Tools: workbook.create_sheet, sheet.append, Font(bold=True), cell.number_format, sheet.freeze_panes, above; table.to_dict("records") gives the rows as dictionaries of column name and value.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| AttributeError: 'NoneType' object has no attribute ... | workbook.active in a workbook with no sheets. |
workbook.create_sheet(title) |
| The sheets in the workbook are wrong, or the earlier sheet's text is gone | The table was written into the open sheet, not a new one. | create_sheet adds one at the end |
| Every value one column to the right of its header, a number first | The rows came from itertuples(), which starts with the index. |
to_dict("records"), or itertuples(index=False) |
The mean household size formatted #,##0 |
The format was chosen by column only. | INDICATORS[record["indicator"]][2] |
nan where an estimate with no value should be empty |
The missing value was written as it is. | None if pd.isna(value) else value |
Header not bold, or panes frozen at is None |
A step left out. | Font(bold=True), freeze_panes = "A2" |
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
Write the header, then each row of the table as values, then give each cell of that row its format from the column's name, or for an estimate and its SE from the row's indicator.
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 add_sheet(workbook: openpyxl.Workbook, title: str, table: pd.DataFrame): """Add a sheet called `title` at the end of the workbook, holding the table: a bold header, the values (a missing one as an empty cell), each numeric column in its Excel number format, the panes frozen below the header. Returns it.""" # Exercise 7.2: the task and examples are in the text above this cell. sheet = workbook.create_sheet(title) sheet.append(list(table.columns)) for cell in sheet[1]: cell.font = Font(bold=True) for record in table.to_dict("records"): sheet.append([None if pd.isna(value) else value for value in record.values()]) for cell, name in zip(sheet[sheet.max_row], table.columns): if name in ("estimate", "se"): cell.number_format = INDICATORS[record["indicator"]][2] elif name in NUMBER_FORMATS: cell.number_format = NUMBER_FORMATS[name] sheet.freeze_panes = "A2" return sheetWhy each part is there
create_sheet(title)adds a sheet at the end and leaves the others alone.workbook.activewould write over whichever sheet is open, and in a workbook with no sheets there is none.to_dict("records")gives each row as a dictionary of column name and value, with no index, so every value lands under its own header.None if pd.isna(value) else valuewrites a missing value as an empty cell, which is what an estimate with no value is in a published table.- The format of
estimateandsefollows the row: in a long table one column holds totals and means, and a mean of 4.31 formatted as#,##0reads as 4. - The values stay numbers. The formats change how Excel shows them, so a reader's formula still adds the full values.
Exercise 7.3. Every table, its three levels stacked
The task
Why it matters: this is the body of the tabulation: every table, at every level, through one helper whose settings are fixed. Written once, the script calls it and writes one workbook; a new table is a line in TABLES, not a new block of code.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| Each sheet holds only the provincial rows | The sheet was set inside the loop over levels, so each level wrote over the one before. | a list of the levels' rows, then one pd.concat per table |
KeyError naming region_code |
The columns were chosen on each level's rows before stacking: the national rows have no codes. | choose the columns after pd.concat |
households_by_scale has no scale column, or it comes before the codes |
The table's own variables left out of by, or put first. |
[*codes, *domains] |
| The mean household size is a total in the tens of thousands | The statistic not taken from the indicator. | INDICATORS[indicator][1] |
| KeyError: 'fishing households' | INDICATORS looked up by the table's name, or TABLES by the indicator's. |
TABLES gives the indicator; INDICATORS[indicator] gives the column and statistic |
No level column |
The levels were stacked without saying which is which. | .assign(level=level) on each level's 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
Loop over the tables, and inside each over the three levels, so that every level's rows come from one call of the helper, by the level's codes and the table's own variables; then stack the levels into the table's sheet.
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_sheets(sample: svy.Sample) -> dict[str, pd.DataFrame]: """Every table of TABLES as one sheet, in that order: its national, regional and provincial rows from estimate(), stacked, with a column level; the columns level, the provincial codes, the table's own variables, then FIGURES.""" # Exercise 7.3: the task and examples are in the text above this cell. sheets = {} for table, (indicator, domains) in TABLES.items(): column, statistic, _ = INDICATORS[indicator] parts = [] for level, codes in LEVEL_CODES.items(): parts.append(estimate(sample, column, statistic, [*codes, *domains]).assign(level=level)) sheets[table] = pd.concat(parts, ignore_index=True)[["level", *LEVEL_CODES["provincial"], *domains, *FIGURES]] return sheetsWhy each part is there
- The loop over
LEVEL_CODESsits inside the loop overTABLES, and its rows go into a list that is stacked once the three levels are in: setting the sheet inside the inner loop would keep only the last level. byputs the level's codes first: the sheet's first columns say where a row is, then what it is cut by. At the national level the codes are an empty list, so a table with no variables of its own is estimated for the whole survey.- Every call goes through
estimate, whose settings are fixed: each sheet has the same figures beside each estimate, and no table can be made with another confidence level by accident. - The columns are chosen after
pd.concat, which fills the codes a level lacks with missing values. Chosen before, on the national rows,region_codewould not exist yet. - The sheet's name is the table's, so the workbook's sheets follow
TABLES: a table added there gets its sheet with no other change.