Skip to content
Learn Python with BNHR

Recode and tabulate

On this page
  1. Overview
  2. 5.1 · Education groups from the code list
  3. 5.2 · A member's role from four flags
  4. 5.3 · Age groups as an ordered category
  5. 5.4 · The top species and "Other"
  6. 5.5 · Distinct units at three levels
  7. 5.6 · One row per operator, with the design columns
  8. 5.7 · An unweighted table with every category

Every exercise in 40_recode_and_tabulate.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 5.1. Education groups from the code list

The task

Why it matters: a table of members or operators by education is one of the survey's standard tables. Driven by the code list, the recode stays right when the list changes; split into No answer and Invalid value, it shows the invalid codes module 4 still has to fix.

Input → output: the members table (its mem_education column) and the code list → a Series with one group per member, in the members' order:

mem_education group
21 Secondary
2 None
(blank) No answer
99 Invalid value

A code in the list gets its group; a blank code gets "No answer"; a code not in the list gets "Invalid value".

Tools: set_index, .map(), .isna(), .mask() and .fillna(), as sex_category above uses them.

If the check is red: common causes

what you see the usual cause look at
Primary completed, Bachelor's degree: twelve different values The label column was used, not group. education_codes.set_index("code")["group"]
No No answer, many more Invalid value Every missing group filled with one category: blank codes and unknown codes pooled. .mask(codes.isna(), "No answer") before .fillna(...)
No Invalid value, more No answer The same, the other way round. fill the blanks from the code, the rest after
Missing values in the result where No answer and Invalid value should be Nothing filled: .map() leaves both kinds missing. the two fills
Members with no schooling are Invalid value The code list was read again inside the function with the defaults, so the group None became missing. use the education_codes you are given
More values than members A merge with a code list whose codes repeat, or a merge that changed the row order. .map()

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 5.2. A member's role from four flags

The task

Why it matters: the role is a column of the survey's tables of members who fish. A misread order moves a member between two roles, and both rows of the table change: a member who runs a unit and also crews in it is one operator, not one crew member.

Input → output: the members table (its four mem_role_ flags) → a Series with one role per row, in the table's order and with the table's index, by the first rule that holds:

rule, in this order role
mem_role_operator is 1 Runs a unit
mem_role_crew is 1 Crew in the household's unit
mem_role_hired is 1 Crew for others
mem_role_shore is 1 On shore only
all four flags blank No answer
anything else (no flag is 1) Invalid value
operator crew hired shore role
1 1 0 0 Runs a unit
0 1 1 0 Crew in the household's unit
(blank) (blank) (blank) (blank) No answer
0 0 0 0 Invalid value

Tools: .eq(1).fillna(False), .isna().all(axis=1), np.select, ROLES and pd.Series(..., index=...), above.

If the check is red: common causes

what you see the usual cause look at
TypeError: invalid entry 0 in condlist: should be boolean ndarray A condition still has missing values. .eq(1).fillna(False) on each flag
The first case's member 1 is Crew in the household's unit Crew came before running a unit in the lists. the operator's flag first
The first case's member 4 is Crew for others Hired came before crew. the order of ROLES
No No answer: the members with every flag blank are Invalid value The "all blank" condition is missing. members[flags].isna().all(axis=1)
Right values, but the check fails on a filtered table The result has a fresh index (0, 1, 2...) instead of the members'. pd.Series(..., index=members.index)

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 5.3. Age groups as an ordered category

The task

Why it matters: the age group is a column of most of the survey's tables of people, and it is the column that shows most often when a table's rows are sorted wrong. Built once as an ordered category, it sorts right in every table, chart and export after it.

Input → output: a Series of ages (such as mem_age) → a Series of type category, ordered, with these eight categories in this order, one value per age, in the ages' order:

category ages
Under 10 0 to 9
10-17, 18-29, 30-44, 45-59 groups that each include their lower age
60 and over 60 to 110
Invalid value an age below 0 or over 110
No answer a missing age

Every category is there even when no age falls in it.

Tools: pd.cut with bins=, right=False and labels=, .cat.add_categories, .mask, above.

If the check is red: common causes

what you see the usual cause look at
10 is Under 10 and 18 is 10-17 right=True, the default. right=False
110 is Invalid value The last edge is 110: with right=False, 110 is outside [60, 110). the last edge, 111
TypeError: Cannot setitem on a Categorical with a new category A catch-all assigned before it was added as a category. .cat.add_categories first
The check shows an AttributeError about .cat The result is text, not a category. return what pd.cut gave, with its categories
Categories in another order, or not ordered The categories were rebuilt from the values, which sorts them as text. keep pd.cut's categories and add to them
130 is No answer, or the blank age is Invalid value Both catch-alls taken from the group's missing value. look at ages.isna()

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 5.4. The top species and "Other"

The task

Why it matters: the table of fishing units by species names the species that matter to the fishery and pools the rest. A ranking rule written down, ties included, gives the same eight species every time the table is run, and an invalid code stays visible instead of disappearing into "Other".

Input → output: the catch table (its catch_species), the species code list and n → a Series with one label per catch row, in the catch table's order:

  1. Names. A code in the species list has its name.
  2. Rank. Count the catch rows of each code that is in the list and whose group is not "Other". The n codes with the most rows are the top; at a tie, the smaller code first.
  3. Labels. A top code keeps its name. A missing code is "No answer"; a code not in the list is "Invalid value". Every other row is "Other".
catch_species label, n = 2 (in a table where 304 and 101 are caught most)
304 Threadfin breams
101 Sardines
203 Other
998 Other
150 Invalid value

Tools: .isin(), value_counts(), sort_values with two columns and ascending=[False, True], .head(n), .map(), .where() and .mask(), above.

If the check is red: common causes

what you see the usual cause look at
Not identified is among the top The group filter is missing: codes 997 and 998 were ranked. species["group"] != "Other"
The first case is red at second place, or the case of region 04 at sixth A tie broken by the order pandas met the codes in, not by code. sort_values(["count", "code"], ascending=[False, True])
No Invalid value, more Other The invalid codes pooled into Other: the catch-alls were set before .where, or not at all. the two .mask calls last
No answer where a code is invalid The two catch-alls swapped: look at whether the code itself is missing. codes.isna()
Codes (304) instead of names The top codes kept as they are. .where on the names, not the codes
n + 1 or more names Every species tied at the boundary kept. .head(n) after sorting

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 5.5. Distinct units at three levels

The task

Why it matters: this is the first table of every survey report: how many households, fishing units or operators, nationally, by region and by province. Written once for any unit, it gives all three counts from any of the survey's tables, and none of the three ways rows mislead can reach it.

Input → output: a table with region_code and province_code, and key, the list of columns that identify the unit within its region's database (["hh_id"] for a household) → one row per area, with three columns:

level area units
National All regions …
Region 01 …
Province 01033 …
  • area: "All regions" for the national row; the region code for a region; the region and province codes joined ("01" + "033") for a province.
  • units: the number of distinct units. A unit is region_code plus the key: the same hh_id in two regions is two households.

Tools: drop_duplicates, groupby(...).size(), len, pd.concat (module 2), above. The row order does not matter.

If the check is red: common causes

what you see the usual cause look at
The national count is below the regions' sum The region is not in the unit's key, so ids shared by two regions were counted once. ["region_code", *key]
Counts equal the table's rows Rows counted, not units. drop_duplicates first
One column per key part, or TypeError: Index(...) must be called with a collection of some kind at .rename("units") nunique given several columns counts each column on its own, and gives a table, not one column. drop_duplicates(...), then size()
The fixture's fishing units are 4, not 5 Duplicates were dropped on fewer columns than the key, so two units of one household merged. ["region_code", *key], every part
A province's area is 033 The region code was not joined to the province code. region_code + province_code
KeyError: 'province_code' in the Try it cell The table was given without its province. with_province(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 5.6. One row per operator, with the design columns

The task

Why it matters: this is the join every estimate in module 6 rests on. One row too many and an operator's weight counts twice; one join key too few and households of different regions trade weights.

Input → output: the members table and the design frame → one row per operator (a member whose mem_role_operator is 1), with at least these columns:

from the members from the design frame
region_code, hh_id, mem_line (the operator's key) province_code
mem_sex, mem_age, mem_education (sex, age, education) stratum_id, psu_id, psus_in_stratum
sel_final_weight

Keep every operator, even one whose household has no row in the design frame: its design columns stay missing, so the gap shows instead of the operator disappearing. Join on the household's whole key, and let pandas check that each operator finds one household at most.

Tools: a boolean filter (== 1), column selection, and merge with on=, how= and validate= (module 2), above.

If the check is red: common causes

what you see the usual cause look at
MergeError: Merge keys are not unique in right dataset Joined on hh_id alone: the id repeats across regions, and validate= caught it. on=["region_code", "hh_id"]
KeyError: "['region_code'] not in index" in the check Joined on hh_id alone without validate=: both tables' region_code came back as region_code_x and region_code_y. the join key
The fixture's operators in household 5103 of region 07 are missing An inner join dropped them. how="left"
Thousands of rows: every member The operators were not filtered. members["mem_role_operator"] == 1
KeyError naming a design column The design frame's column was not selected, or its name was misread (sel_ea is the area's number; psu_id is the course's PSU id). the five design 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 5.7. An unweighted table with every category

The task

Why it matters: the unweighted table is the first one checked against the field reports (how many operators were interviewed in each group) and the one module 6's estimates sit beside. It must list every category, in order, with its totals.

Input → output: the frame (one row per unit) and the names of two of its columns → the number of rows in each combination, with:

  • one row per category of the rows column and one column per category of the columns column, empty categories included, in the categories' order;
  • a last row and a last column named "Total".
age_group Male Female Invalid value No answer Total
Under 10 … … 0 0 …
… … … … … …
Total … … … … …

Tools: pd.crosstab with dropna=False, margins=True and margins_name="Total", above.

If the check is red: common causes

what you see the usual cause look at
No Invalid value or No answer column; fewer rows Empty categories dropped, the default. dropna=False
No Total row or column The margins are missing. margins=True
A row and column named All pandas' default name for the margins. margins_name="Total"
Age groups in the order 10-17, 60 and over, Under 10 The category column was turned into text, which sorts by letter. pass the categorical columns as they are
The counts are weights values= and aggfunc="sum" summed a weight: that is module 6's estimate, not a count. count rows only

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 primer
Primer P1Primer: marimo and the Python this course assumes
AboutA primer of Arrays & DataFrames, for any time: how a marimo notebook runs, how the course's exercises work, the Python the course assumes, and how to read an error.
CourseArrays & DataFrames, free