Skip to content
Learn Python with BNHR

Module 7: Publish the tables

On this page
  1. Overview
  2. 7.1 · Every level in one long table
  3. 7.2 · A sheet with a header, number formats and frozen panes
  4. 7.3 · Every table, its three levels stacked

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's region) 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.

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: estimate and se in the format of the row's indicator (INDICATORS[indicator][2]: "#,##0" for totals, "0.00" for the mean); every other column named in NUMBER_FORMATS (cv as "0.0%", n as "#,##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.

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.

Something new

Identify results
LayerExplore a module
ModuleMatch the keys
AboutModule 3 of Python for Survey Statistics: matching the keys between tables: orphans in every child table, operators against the members roster, the automated and the manual repair, and edits written back with an audit flag. Its sections, its notebooks to read on the web, and the companion's solutions and explanations.
CoursePython for Survey Statistics, free