Skip to content
Learn Python with BNHR

Start here

On this page
  1. Overview
  2. 1.1 · The codes of a variable
  3. 1.2 · Is it a PSGC code?
  4. 1.3 · Households represented
  5. 1.4 · Plots by crop, in the library of your choice
  6. 1.5 · Any column, by province

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. The codes of a variable

The task

Why it matters: a codebook writes its codes as text, such as 1 = Male; 2 = Female; 9 = Not stated. Turned into a dictionary, they can label a table or a chart, and tell you which values to treat as missing.

Input → output: the values text of one codebook row → a dictionary of each code and what it means.

values returns
"1 = Male; 2 = Female; 9 = Not stated" {"1": "Male", "2": "Female", "9": "Not stated"}
"999 = Not stated" {"999": "Not stated"}
"Rice; Corn; Vegetables; Banana; blank = not recorded" {"blank": "not recorded"}
'' (empty: a variable with no codes) {}

The parts are separated by "; " (a semicolon and a space). A part written code = meaning becomes one entry; a part without " = ", such as Rice, is a value that means itself, and is left out. The codes stay text, as written: "1", not 1.

Tools (Python Essentials, modules 3 to 6): text.split("; ") gives the list of parts; " = " in part is True when the part holds =; part.split(" = ", 1) splits at the first = only, into two pieces, and code, meaning = ... names them; meanings[code] = meaning stores an entry in a dictionary.

If the check is red: common causes

what you see the usual cause look at
ValueError: too many values to unpack (expected 2, got 3) The part sqm = square meters (1 ha = 10,000 sqm) holds two =; splitting at both gives three pieces for two names. part.split(" = ", 1): split at the first only
ValueError: not enough values to unpack (expected 2, got 1) A part without =, such as Rice, was split too. if " = " in part: before splitting
Codes such as " 2", with a space in front The text was split at ";" without its space. values.split("; ")
Only the first code comes back return is inside the loop, so the function ends after the first part. move return meanings out of the loop, to the function's own indentation
None The function has no return, or prints the dictionary instead. end with return meanings

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 1.2. Is it a PSGC code?

The task

Why it matters: a code that went through a number column or was typed by hand comes back damaged in ways that are easy to miss: its leading zero lost, .0 added when a number was turned back into text, a space at the end, the letter O typed for a zero. A test that a code is still 10 digits catches all of them, before the code is used to join or group.

Input → output: a code, as text → True when it is exactly 10 characters, every one a digit; False otherwise.

code returns why
"0102820000" True 10 digits
"102820000" False 9 digits: the leading zero was lost
"O102820000" False 10 characters, but the first is the letter O, not a zero

Tools (Python Essentials, modules 2 and 6): len(code) is the number of characters; code.isdigit() is True when every character is a digit; and is True only when both sides are.

If the check is red: common causes

what you see the usual cause look at
True for 'O102820000' Only the length is tested. add code.isdigit()
True for '102820000' Only the digits are tested. add len(code) == 10
True for '0102820000 ' The space was removed before testing. The task asks about the code as it is. test code itself, without .strip()
False for '1204701000' The code is tested for a leading 0. Codes from Region X onward start with 1. test the length and the digits, not the first character
TypeError: object of type 'int' has no len() Your own test gave the function a number; codes are text, and the check gives text only. call it with text: is_psgc_code("0102820000")

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 1.3. Households represented

The task

Why it matters: "how many farm households are there in this province?" is a sum of weights, not a count of interviews. Counting the rows answers a different question: how many were interviewed.

Input → output: a list of households, each a dictionary with at least "province" and "weight", and a province's name → the sum of the weights of that province's households, rounded to a whole number; 0 when none is in that province.

records = [
    {"hh_id": "A", "province": "Iloilo", "weight": 250.4},
    {"hh_id": "B", "province": "Iloilo", "weight": 310.2},
    {"hh_id": "C", "province": "Bukidnon", "weight": 512.75},
    {"hh_id": "D", "province": "Iloilo", "weight": 99.1},
]
households_represented(records, "Iloilo")    # 660: 250.4 + 310.2 + 99.1 is 659.7, rounded
households_represented(records, "Cotabato")  # 0

Tools (Python Essentials, modules 3 to 5): a total that starts at 0; for record in records:; if record["province"] == province:; round(value), which rounds to the nearest whole number.

If the check is red: common causes

what you see the usual cause look at
3 for Iloilo in the four households The function counts the households instead of adding their weights. total = total + record["weight"]
659.7 for Iloilo The total is not rounded. return round(total)
659 for Iloilo int(...) cuts the decimals off instead of rounding. round(total)
250 for Iloilo return is inside the loop, so the function stops at the first household. return at the function's own indentation, after the loop
The same total for every province The if is missing, so every household is added. if record["province"] == province:
KeyError: 'Weight' The key is spelled differently from the dictionaries'. Keys are exact, lower case included. record["weight"], record["province"]

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 1.4. Plots by crop, in the library of your choice

The task

Why it matters: each library asks for the same chart in its own terms. Drawing one yourself, from a table you have not charted yet, is how you learn which terms.

Input → output: a table with a crop column and a plots column → a bar chart with one bar per crop, as long as its number of plots. Return the chart: the axes for matplotlib or seaborn, the Chart for Altair.

crop plots
Rice 12
Corn 5

gives two bars, Rice 12 long and Corn 5. The survey's own table is under this text; the Try it cell charts it.

Use any one of the three libraries: the check compares the bars drawn (each bar's crop and its length), not the picture, so titles, colors and whether the bars run up or across are yours to choose.

Tools: the three functions above. In matplotlib, ax.bar(x values, heights) draws upright bars and ax.barh(...) bars across; in seaborn, sns.barplot(data=table, x=..., y=..., errorbar=None, ax=ax); in Altair, alt.Chart(table).mark_bar().encode(x=..., y=...). For matplotlib and seaborn, make a fresh figure inside the function: fig, ax = plt.subplots().

If the check is red: common causes

what you see the usual cause look at
TypeError: chart_data reads a matplotlib, seaborn or Altair chart, not a builtins.NoneType The function draws the chart but does not return it. the last line: return ax (matplotlib, seaborn), return the Chart (Altair)
Some tables are right, others show extra bars The bars were drawn on a chart already there (seaborn without ax=, or plt.bar), so each table's bars pile onto the ones before. fig, ax = plt.subplots() inside the function, and ax=ax for seaborn
Every bar is 1 long The chart counts the rows (seaborn's countplot, Altair's count()) instead of drawing the plots column. ax.bar(table["crop"], table["plots"]), or y="plots"
KeyError: 'Crop' (matplotlib), Could not interpret value Crop (seaborn) or Unable to determine data type for the field "Crop" (Altair) A column name that is not in the table. Names are exact, lower case included. the columns: crop and plots
Right for the survey's table, wrong for the small ones The function charts plots_per_crop instead of its input. use table everywhere inside the function
0 of 3 tables are right, and the chart shows a line A line chart (ax.plot, sns.lineplot, mark_line): the check reads bars. ax.bar, sns.barplot, mark_bar

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 1.5. Any column, by province

The task

Why it matters: a chart function that takes the column to draw as an input works for every column of the table. It is also where a common slip shows: the input column holds a column's name, so it is written without quotes.

Input → output: a table with a province column, and the name of another of its columns → a bar chart with one bar per province, as long as that column's value.

call draws
province_chart(by_province, "farm_households") the chart above, in any library
province_chart(by_province, "interviewed") seven bars, all 170 long

Tools: as in Exercise 1.4. Where the examples write "farm_households", write column: table[column] in matplotlib, x=column in seaborn and Altair.

If the check is red: common causes

what you see the usual cause look at
KeyError: 'column' The input's name is written in quotes, table["column"], so pandas looks for a column called column. table[column], without quotes
Could not interpret value column (seaborn) or Unable to determine data type for the field "column" (Altair) The same, in seaborn or Altair: x="column". x=column
Right for farm_households, wrong for interviewed The function still names the example's column instead of using its input. every place a column is named, except "province"
Right for by_province, wrong for the two-province table The function charts by_province instead of its input. use table everywhere inside the function
Some cases are right, others show extra bars The bars pile onto a chart already there. fig, ax = plt.subplots() inside the function, and ax=ax for seaborn
TypeError: chart_data reads … not a builtins.NoneType No return. return ax, or return the Chart

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
ModuleCharts and sharing
AboutModule 7 of Arrays & DataFrames: the chart that answers the question honestly, choosing between matplotlib, seaborn and Altair, and a small interactive marimo app. Its sections, its notebooks to read on the web, and the companion's solutions and explanations.
CourseArrays & DataFrames, free