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.
The idea
The code list's group column is the recode: map the codes through it, then tell the two kinds of missing group apart by looking back at the code, blank or not.
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 education_group(members: pd.DataFrame, education_codes: pd.DataFrame) -> pd.Series: """Each member's education group from the code list: its group, No answer for no code, Invalid value for a code not in the list.""" # Exercise 5.1: the task and examples are in the text above this cell. codes = members["mem_education"] groups = codes.map(education_codes.set_index("code")["group"]) return groups.mask(codes.isna(), NO_ANSWER).fillna(INVALID)Why each part is there
education_codes.set_index("code")["group"]turns the code list into a lookup. A new code in the list changes the recode with no change to this function..map(lookup)keeps the members' order and length: one group per member. A merge would also work, but it returns a new table that must be lined up again..mask(codes.isna(), "No answer")first: a blank code is a question nobody asked (members under 6 are not asked about education), not an error..fillna("Invalid value")last: the only missing groups left are codes the list does not have, such as99. Filling every missing group with one category would hide them among the blanks.
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.
The idea
A rule read in order is np.select: the first true condition gives the role. The flags are nullable, so each condition is made plain True or False first, and "all blank" is its own condition, separate from "no flag is 1".
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 fishing_role(members: pd.DataFrame) -> pd.Series: """Each member's role from the flags mem_role_operator, mem_role_crew, mem_role_hired and mem_role_shore, in that order; No answer if all four are blank, Invalid value if none is 1.""" # Exercise 5.2: the task and examples are in the text above this cell. flags = ["mem_role_operator", "mem_role_crew", "mem_role_hired", "mem_role_shore"] conditions = [members[flag].eq(1).fillna(False) for flag in flags] + [members[flags].isna().all(axis=1)] return pd.Series(np.select(conditions, [*ROLES, NO_ANSWER], default=INVALID), index=members.index)Why each part is there
.eq(1).fillna(False): a blank flag gives a missing condition, andnp.selectrefuses missing values. A blank is not a yes, so False is right.- Running a unit is the first condition, so a member with
mem_role_operatorandmem_role_crewboth 1 runs a unit. Put crew first and the same row becomes crew: the order of the list is the rule. isna().all(axis=1)is true only where all four flags are missing: those members were not asked, or did not answer (No answer). A member with every flag 0 answered, and said they did none of the four, so that row falls to the default.pd.Series(..., index=members.index):np.selectgives an array with no index; the index puts each role back beside its member, even when the table was filtered.
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.
The idea
pd.cut sorts the ages into ranges and returns an ordered category in the bins' order; the two catch-alls are added as categories, then given to the ages pd.cut left without a group, split by whether the age was there.
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 age_group(ages: pd.Series) -> pd.Series: """Ages in the survey's age groups, as an ordered category: Under 10 to 60 and over, then Invalid value and No answer.""" # Exercise 5.3: the task and examples are in the text above this cell. groups = pd.cut(ages, bins=[0, 10, 18, 30, 45, 60, 111], right=False, labels=["Under 10", "10-17", "18-29", "30-44", "45-59", "60 and over"]) groups = groups.cat.add_categories([INVALID, NO_ANSWER]) return groups.mask(ages.notna() & groups.isna(), INVALID).mask(ages.isna(), NO_ANSWER)Why each part is there
right=Falsemakes each range[low, high): 10 is in "10-17" and 18 is not. With the default, 10 would be "Under 10" and 18 "10-17", every boundary one group off.- The last edge is 111, not 110: with
right=False, an age of 110 must be below the last edge to be in "60 and over". .cat.add_categories([...])first: a categorical refuses a value that is not one of its categories, so the catch-alls must exist before they are assigned. Added at the end, they sort after the age groups.ages.notna() & groups.isna()are the ages outside every range;ages.isna()the blanks.pd.cutgives both a missing group, so the age itself tells them apart.
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:
- Names. A code in the species list has its
name. - Rank. Count the catch rows of each code that is in the list and whose
groupis not"Other". Thencodes with the most rows are the top; at a tie, the smaller code first. - 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.
The idea
Rank only the codes that may rank, by catch rows with a written tie rule, keep the first n, and label every row from that list; the two catch-alls are set last so no rule can pool them into "Other".
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 top_species(catch: pd.DataFrame, species: pd.DataFrame, n: int) -> pd.Series: """Each catch row's species name if it is one of the n named species caught most (ties: smaller code first), else Other; No answer for a missing code and Invalid value for a code not in the list.""" # Exercise 5.4: the task and examples are in the text above this cell. codes = catch["catch_species"] names = codes.map(species.set_index("code")["name"]) may_rank = codes[codes.isin(species.loc[species["group"] != "Other", "code"])] counts = may_rank.value_counts().rename_axis("code").reset_index() top = counts.sort_values(["count", "code"], ascending=[False, True])["code"].head(n) labels = names.where(codes.isin(top), "Other") return labels.mask(codes.notna() & names.isna(), INVALID).mask(codes.isna(), NO_ANSWER)Why each part is there
species.set_index("code")["name"]is the lookup, as in Exercise 5.1; a code it lacks gets no name, which is how step 3 finds the invalid codes.isin(...)with the group filter leaves out "Other species, to be named" and "Not identified" before ranking. In a small table they can have the most rows, as "Not identified" does in the check's first case, and they would take a place no reader can use.sort_values(["count", "code"], ascending=[False, True])writes the tie rule down.value_counts().head(n)alone breaks a tie by whatever order pandas met the codes in, which a filter or a new batch of data can change..where(codes.isin(top), "Other")keeps a top species' name and pools the rest. The two.maskcalls come after it, so an invalid code ends as "Invalid value", not "Other".
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 isregion_codeplus the key: the samehh_idin 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.
The idea
Keep each unit once, by its whole key with the region in it, then count rows at each level: after drop_duplicates, a row is a unit, so a row count is a unit count.
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 distinct_by_level(table: pd.DataFrame, key: list) -> pd.DataFrame: """The number of distinct units (region_code plus key) nationally, by region and by province: level, area, units.""" # Exercise 5.5: the task and examples are in the text above this cell. unit = ["region_code", *key] found = table[["province_code", *unit]].drop_duplicates(subset=unit) national = pd.DataFrame({"level": ["National"], "area": ["All regions"], "units": [len(found)]}) regional = found.groupby("region_code").size().rename("units").reset_index() regional = regional.assign(level="Region", area=regional["region_code"]) provincial = found.groupby(["region_code", "province_code"]).size().rename("units").reset_index() provincial = provincial.assign(level="Province", area=provincial["region_code"] + provincial["province_code"]) columns = ["level", "area", "units"] return pd.concat([national[columns], regional[columns], provincial[columns]], ignore_index=True)Why each part is there
["region_code", *key]: a household id is unique only in its region's database, so the region is part of every unit's key. Without it, the national count merges households of different regions that share an id.drop_duplicateson the key withprovince_codekeeps one row per unit: the rows a unit has by design (its fishing units, its catch) and those entered twice both collapse to one.groupby(...).size()on the units counts units.nuniquewould also work for a one-column key, but given several columns it counts each column on its own.region_code + province_codemakes a province's area unique across regions and matches the first five digits of its PSGC code.
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.
The idea
Filter to the unit first, then bring the household's design columns with a left join on the household's whole key, checked to match at most one household: the frame keeps the operators' rows, no more and no fewer.
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 operator_frame(members: pd.DataFrame, design: pd.DataFrame) -> pd.DataFrame: """One row per operator: key, sex, age and education from the members; province, stratum_id, psu_id, psus_in_stratum and sel_final_weight from the design frame.""" # Exercise 5.6: the task and examples are in the text above this cell. columns = ["region_code", "hh_id", "mem_line", "mem_sex", "mem_age", "mem_education"] design_columns = ["region_code", "hh_id", "province_code", "stratum_id", "psu_id", "psus_in_stratum", "sel_final_weight"] found = members.loc[members["mem_role_operator"] == 1, columns] return found.merge(design[design_columns], on=["region_code", "hh_id"], how="left", validate="many_to_one")Why each part is there
members["mem_role_operator"] == 1keeps the operators: the unit of the operators' tables. A blank flag is not 1, so a member who was not asked is left out. Joining every member and filtering later works too, but carries thousands of rows for nothing.on=["region_code", "hh_id"]: the household's id repeats across regions. Joined onhh_idalone, an operator in region 01 matches the households with that id in 04 and 07 as well, and takes their weights.validate="many_to_one"writes down that many operators share one household and no operator has two. With the region left out of the key, pandas stops with a MergeError instead of multiplying rows.how="left"keeps an operator whose household has no design row, with missing design columns that the next cell counts. An inner join would drop them, and the operators' total with them, without a word.
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
rowscolumn and one column per category of thecolumnscolumn, 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.
The idea
crosstab counts rows per cell; with categorical columns it lists their categories in order, and dropna=False keeps the ones no row has, so the table's shape comes from the categories, not from the data.
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 unweighted_table(frame: pd.DataFrame, rows: str, columns: str) -> pd.DataFrame: """Rows of the frame counted by two columns: every category, empty ones included, in order, with Total row and column.""" # Exercise 5.7: the task and examples are in the text above this cell. return pd.crosstab(frame[rows], frame[columns], dropna=False, margins=True, margins_name="Total")Why each part is there
- The frame has one row per operator, so a count of rows is a count of operators. Built on a table with several rows per unit, the same call would count rows.
dropna=Falsekeeps the empty categories. By defaultcrosstabdrops a category no row has, so the table's rows change from one region or batch to the next.margins=Trueadds the totals;margins_name="Total"names them as the table prints them. The total row counts every operator once, since each is in one row and one column.