Every exercise in 00_start.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 1.1. Codes that are not on the list
The task
Why it matters: a code outside its list is a keying slip or a code the list forgot. Either way an editor must see it before tabulating, or a table gets a row nobody can label. A blank is a different thing: the education level is blank for members under six, because the question is not asked of them. Reported as an invalid code, every young child would become an edit to make.
Input → output: a column of codes and the list of valid codes → the codes in the column that are not on the list, each once, smallest first, with blanks (missing values) left out. [] when every code is valid.
column |
valid |
returns |
|---|---|---|
[1, 2, 9, <NA>, 3, 9] |
[1, 2] |
[3, 9] |
[1, 2, 2, 1] |
[1, 2] |
[] |
Tools (Arrays & DataFrames, modules 3 and 5): column.dropna() leaves out the blanks; column.isin(valid) is True where a value is on the list, and ~ turns each True to False and back; .unique(); .tolist(); sorted(...).
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| TypeError: boolean value of NA is ambiguous | A blank reached sorted, which cannot compare it with a number. |
column.dropna() before anything else |
[3, 9, None] or a blank in the list |
The blanks were kept: isin is False for a blank, so ~ keeps it. |
column.dropna() |
[9, 3] |
Each code once, but in the order they first appear. | sorted(...) |
[9, 3, 9] |
One entry per row, not per code. | .unique() |
[1, 2]: the valid codes |
The ~ is missing, so the values on the list are kept. |
~present.isin(valid) |
| A column of values shown, not a list | The filtered column was returned as it is. | .unique().tolist(), then sorted |
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
Drop the blanks first, keep the values the list does not have, and return each of those once, sorted.
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 codes_outside(column: pd.Series, valid: list) -> list: """The codes in a column that are not in the list of valid codes: each once, smallest first, blanks left out.""" # Exercise 1.1: the task and examples are in the text above this cell. present = column.dropna() return sorted(present[~present.isin(valid)].unique().tolist())Why each part is there
column.dropna()comes first because a blank is not on any list:isingivesFalsefor it,~makes thatTrue, and the blank would be reported as an invalid code.- With the blanks in,
sortedfails as well, with TypeError: boolean value of NA is ambiguous: it cannot say whether a missing value is smaller than 3. ~present.isin(valid)keeps the values that are not on the list. Without the~the function returns the valid codes instead..unique()gives each code once, however many rows hold it;.tolist()makes a plain list, andsortedputs it smallest first.
Exercise 1.2. Step 1, filter: the large-scale units that are not voided
The task
Why it matters: every count of large-scale units starts from this filter. Written the dplyr way without the blank in mind, it keeps no row at all, and every table after it comes out empty with no error.
Input → output: a fishing units table as the database holds it → its rows whose unit_scale is 2 and whose row_void is blank or not 1, every column kept.
| region_code | hh_id | unit_scale | row_void | kept? |
|---|---|---|---|---|
| 01 | 5012 | 2 | blank | yes |
| 01 | 5013 | 2 | 1 | no: voided in editing |
| 04 | 5204 | 1 | blank | no: small-scale |
| 07 | 5088 | 2 | blank | yes |
In R: units |> filter(unit_scale == 2, is.na(row_void) | row_void != 1).
Tools: the keep rows and is blank rows of the translation table: table[(condition) & (condition)], .isna(), and | for or, with brackets around each comparison.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| 0 rows for the survey | row_void != 1 alone: it is blank for a blank mark, and a row with a blank condition is dropped. Or row_void == 0: the mark is never 0. Or units["row_void"].isna() | units["row_void"] != 1 with no brackets around the comparison: | is worked out before !=, with no error. |
units["row_void"].isna() | (units["row_void"] != 1) |
| The second of the five units is kept | The void mark is not tested. | the second condition |
Small-scale units (unit_scale 1) are kept |
The scale is not tested, or tested with != 1 on a column that could hold other values. |
units["unit_scale"] == 2 |
| TypeError: Cannot perform 'rand_' ... or TypeError: 'other' should be pandas.NA or a bool | A comparison without its own brackets: & and | are worked out before == and !=. |
a pair of brackets around each comparison |
| ValueError: The truth value of a Series is ambiguous | and or or between two columns of conditions, or two comparisons chained without brackets. |
& and |, and brackets |
| Fewer columns than the input | Columns were selected after the filter. | return units[...] with every column |
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
Two conditions joined with &: large-scale, and not voided. Not voided is itself two cases joined with |, because a blank row_void is not unequal to 1 but unknown.
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 large_scale_units(units: pd.DataFrame) -> pd.DataFrame: """The fishing units whose scale is 2 (a boat of 5.0 gross tons or more) and that are not voided.""" # Exercise 1.2: the task and examples are in the text above this cell. return units[(units["unit_scale"] == 2) & (units["row_void"].isna() | (units["row_void"] != 1))]Why each part is there
units["row_void"].isna() | (units["row_void"] != 1)keeps a blank mark.units["row_void"] != 1alone is blank (<NA>) for a blank mark, and pandas drops a row whose condition is blank, as dplyr does: on the survey's units, whose marks are all blank, it keeps no row at all.- Testing
units["row_void"] == 0keeps nothing either: the mark is 1 or blank, never 0. - Each comparison has its own brackets. Without them Python works out
&before==, and the line fails or tests something else. units[...]returns the rows with every column, as the task asks; their index labels are the original rows', which the check does not compare.
Exercise 1.3. Step 2, mutate: each boat's gross tonnage
The task
Why it matters: a unit is large-scale when one of its boats is 5.0 gross tons or more, so the tonnage decides which table every unit is counted in. The questionnaire takes a boat's size from its registration papers, or measures it in meters or in feet (boat_measured_in), and the formula depends on which. The capture program stores a tonnage too (boat_tonnage), but stored figures can be wrong; computing it again is how module 4 checks them.
Input → output: a boats table → the same table with one more column at the end, gt, the boat's gross tonnage, by rule B3 of codebook_rules.csv:
boat_measured_in, where the size comes from |
gt |
|---|---|
| 1, the registration papers | boat_tonnage_reported, the tonnage on the papers |
| 2, measured in meters | boat_length × boat_beam × boat_depth × 0.212 |
| 3, measured in feet | boat_length × boat_beam × boat_depth × 0.006 |
For example, a boat measured in meters, 10 long, 1 wide and 0.5 deep, is 10 × 1 × 0.5 × 0.212 = 1.06 gross tons. Mind the order of the codes: 1 is the papers, not meters.
In R:
boats |> mutate(gt = case_when(
boat_measured_in == 1 ~ boat_tonnage_reported,
boat_measured_in == 2 ~ boat_length * boat_beam * boat_depth * 0.212,
boat_measured_in == 3 ~ boat_length * boat_beam * boat_depth * 0.006
))
Tools: the a column by cases row of the translation table: np.select([conditions], [values], default=np.nan), the conditions and the values in the same order; table.assign(gt=...) returns the table with the new column.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| About 38 for the second small boat, not 1.08 | Feet multiplied by 0.212, the factor for meters. | * 0.006 for a boat measured in feet |
A blank gt for the third small boat |
Only two cases (an np.where on meters or feet): the papers' tonnage is never taken. |
a condition boat_measured_in == 1, with boat_tonnage_reported |
| 0.03 for the first small boat, and blanks for the next two | The codes read in another order (1 as meters, 2 as feet, 3 as the papers). | the codebook's values for boat_measured_in: 1 is the papers |
| 4.8 for the fourth small boat | The stored boat_tonnage was copied; it is wrong for that boat. |
compute boat_length * boat_beam * boat_depth * 0.212 |
| ValueError: list of cases must be same length as list of conditions | np.select was given three conditions and two values, or the other way round. |
the two lists, in the same order |
No gt column, or gt not last |
The result was not added as a column, or the columns were reordered. | boats.assign(gt=...) |
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
case_when in pandas: three conditions on where the boat's size comes from, each with its own value, picked row by row by np.select, and added as a column with assign.
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 with_gross_tonnage(boats: pd.DataFrame) -> pd.DataFrame: """The boats table with one more column, gt: the gross tonnage from the papers, from meters or from feet, by boat_measured_in.""" # Exercise 1.3: the task and examples are in the text above this cell. source = boats["boat_measured_in"] volume = boats["boat_length"] * boats["boat_beam"] * boats["boat_depth"] return boats.assign(gt=np.select([source == 1, source == 2, source == 3], [boats["boat_tonnage_reported"], volume * 0.212, volume * 0.006], default=np.nan))Why each part is there
- Both products are computed for every boat;
np.selectthen takes, row by row, the value whose condition holds. A boat whose size comes from its papers has blank dimensions, so its products are blank, andnp.selectnever picks them. - Feet take 0.006, not 0.212: a meter is about 3.28 feet, so a cubic meter is about 35.3 cubic feet, and 0.212 ÷ 35.3 is 0.006. The two factors give one boat the same tonnage whichever unit it was measured in. With 0.212, a boat of 30 × 3 × 2 feet comes out at 38.16 gross tons instead of 1.08.
- The first condition takes the tonnage from the papers,
boat_tonnage_reported. A two-waynp.whereon meters or feet would give a blank or a wrong tonnage to every boat measured from its papers. - It computes the tonnage instead of copying the stored
boat_tonnage: the stored figure is rounded to hundredths, and some stored values are wrong, which the check's small table includes. assignreturns a new table withgtas its last column and leaves the input as it was.
Exercise 1.4. Step 3, inner_join: the catch of the large-scale units
The task
Why it matters: the catch table does not say whether its unit is large-scale; only the units table does. An inner join keeps the catch rows whose unit is in the large-scale set and drops the rest. It needs the whole key: without region_code a household of region 01 matches the household with the same id in region 07, and without unit_no a member's second unit matches their first.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| KeyError: 'operator_line' | The catch's key parts still have their catch_ names. |
catch.rename(columns=CATCH_KEY) first |
| A row of region 07 in the small table's result | region_code is not in the key, so household 5012 of region 07 matched region 01's. |
all four parts: on=UNIT_KEY |
Species 203 in the small table's result |
unit_no is not in the key, so the member's second unit matched the first. |
all four parts |
Species 101 in the result, or a row with a blank species |
A left or outer join: unmatched rows were kept. | how="inner" |
Columns such as row_id_x and row_id_y, or more than five columns |
The whole units table was joined, or the five columns were not selected. | units[UNIT_KEY], then [UNIT_KEY + ["catch_species"]] |
| MergeError: Merge keys are not unique in right dataset | A unit is in the units table twice. The check gives none; your own call may have used every unit, with the copy shown above. | the units with the copy dropped, as large is |
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
Give the catch's key parts the unit's names, then keep the catch rows whose four-part key is in the units table: an inner join on the whole key, checked to be many catch rows to one unit.
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 catch_of(units: pd.DataFrame, catch: pd.DataFrame) -> pd.DataFrame: """The catch rows of the given fishing units, joined on the whole unit key: UNIT_KEY's four columns and catch_species.""" # Exercise 1.4: the task and examples are in the text above this cell. matched = catch.rename(columns=CATCH_KEY).merge(units[UNIT_KEY], on=UNIT_KEY, how="inner", validate="many_to_one") return matched[UNIT_KEY + ["catch_species"]]Why each part is there
rename(columns=CATCH_KEY)makes the names match, so oneon=UNIT_KEYserves both tables. Joining withon=UNIT_KEYbefore renaming raises KeyError: 'operator_line', because the catch has no column of that name.- The key has all four parts. Without
region_code, household 5012 of region 07 matches household 5012 of region 01; withoutunit_no, the catch of a member's second unit matches their first. units[UNIT_KEY]brings only the key, so the result has no second copy of the columns both tables have, such asrow_id(which pandas would namerow_id_xandrow_id_y).how="inner"drops the catch rows of units not in the table, and a unit with no catch adds no row. A left join from the catch would keep every catch row; one from the units would add rows with a blank species.validate="many_to_one"stops the join if a unit is in the units table twice, which would repeat its catch rows. The survey has such a copy among its large-scale units; the check's tables leave it out, and module 4 decides about it.left_on=with the catch's names andright_on=UNIT_KEYgives the same rows without renaming, with both sets of key columns in the result; selecting the five columns at the end drops the extra ones.