Exercises
Fifteen exercises covering the whole course, from data types to the quality report. Try each one before opening the answer. Several answers include a program you can run and change; the lesson in brackets is the place to reread if you get stuck.
| # | Exercise | Practises |
|---|---|---|
| 1 | Classify the columns | data types |
| 2 | Features, label and grain | dataset vocabulary |
| 3 | Multi-class or multi-label | annotations and classes |
| 4 | A CSV that lies | CSV reading options |
| 5 | Flatten an API response | JSON and JSON Lines |
| 6 | Features without the future | SQL and leakage |
| 7 | Choose a format | Parquet, CSV, JSONL |
| 8 | Is it still the same dataset? | versioning and manifests |
| 9 | May we use it? | sources, licences, consent |
| 10 | Placeholders and missingness | missing-value analysis |
| 11 | Same customer, three rows | duplicates |
| 12 | Robust outliers | outlier detection |
| 13 | Agreement by chance | label quality |
| 14 | Accuracy on rare classes | class distribution |
| 15 | One rule set, many columns | consistency and reports |
Exercise 1: Classify the columns
A table of hotel bookings has the columns booking_id, check_in (a date), nights, room_type (single, double, suite), star_rating (1–5), price_eur, breakfast (yes/no), country_code, review_text and room_photos (a list of file names). Give each column's type and one thing you must be careful about.
Answer
| Column | Type | Careful about |
|---|---|---|
booking_id |
identifier (nominal) | never a feature; must be unique |
check_in |
date / time | parse with an explicit format; split by time |
nights |
numerical, discrete | 0 or negative values are errors |
room_type |
categorical, nominal | spelling variants; one-hot, not 0/1/2 |
star_rating |
ordinal | keep the order; the gap from 1 to 2 stars is not "the same" as from 4 to 5 |
price_eur |
numerical, continuous | currency and unit in the name; skewed |
breakfast |
binary | many spellings of yes/no |
country_code |
categorical, nominal | codes look like text but are categories with many levels |
review_text |
text | language, encoding, personal data |
room_photos |
images (file references) | broken links, duplicates, EXIF metadata |
See Numerical, Categorical, Binary and Ordinal Data, Text Data and Images, Audio and Video.
Exercise 2: Features, label and grain
A hospital wants to predict at admission whether a patient will be readmitted within 30 days of discharge. The data has one row per lab test, with patient_id, admission_id, test_name, value, admitted_on, discharged_on, length_of_stay and readmitted_30d. What should one row of the training table be, what is the label, and which column must not be a feature?
Answer
One row per admission (aggregate the lab tests per admission_id, using only tests taken before the prediction time). The label is readmitted_30d. length_of_stay and discharged_on are not known at admission, so they must not be features; using them leaks the future. Splits should be by patient_id, so the same patient is not in train and test. See Samples, Features, Labels.
Exercise 3: Multi-class or multi-label
For each task, say whether it is binary, multi-class or multi-label: (a) the species of a bird in a photo of one bird; (b) all diseases visible on a chest X-ray; (c) whether an email is spam; (d) the topics of a news article; (e) the digit in an image of one handwritten digit.
Answer
(a) multi-class, (b) multi-label, (c) binary, (d) multi-label, (e) multi-class. See Ground Truth, Annotations, Classes and Metadata.
Exercise 4: A CSV that lies
Read this file so that zip keeps its leading zeros, amount is a number, "-" counts as missing and date is a real date. Print the dtypes.
zip;amount;date;note
01067;1.234,50;2026-03-01;ok
10115;-;2026-03-02;"late; paid"Answer
import io
import pandas as pd
text = 'zip;amount;date;note\n01067;1.234,50;2026-03-01;ok\n10115;-;2026-03-02;"late; paid"\n'
df = pd.read_csv(io.StringIO(text), sep=";", decimal=",", thousands=".",
dtype={"zip": "string"}, na_values=["-"], parse_dates=["date"], date_format="%Y-%m-%d")
print(df)
print(df.dtypes.to_dict()) zip amount date note
0 01067 1234.5 2026-03-01 ok
1 10115 NaN 2026-03-02 late; paid
{'zip': string[python], 'amount': dtype('float64'), 'date': dtype('<M8[ns]'), 'note': dtype('O')}
The quoted "late; paid" stays one field because the parser respects quotes. See CSV and TSV.
Exercise 5: Flatten an API response
An API returns {"user": "u7", "sessions": [{"start": "09:00", "pages": 4}, {"start": "13:30", "pages": 9}]} per user. Build a table with one row per user and the columns user, n_sessions and total_pages.
Answer
import pandas as pd
records = [
{"user": "u7", "sessions": [{"start": "09:00", "pages": 4}, {"start": "13:30", "pages": 9}]},
{"user": "u8", "sessions": [{"start": "10:15", "pages": 2}]},
{"user": "u9", "sessions": []},
]
per_session = pd.json_normalize(records, record_path="sessions", meta=["user"])
agg = per_session.groupby("user")["pages"].agg(n_sessions="count", total_pages="sum")
users = pd.DataFrame({"user": [r["user"] for r in records]})
print(users.join(agg, on="user").fillna(0).astype({"n_sessions": int, "total_pages": int})) user n_sessions total_pages
0 u7 2 13
1 u8 1 2
2 u9 0 0
User u9 has no sessions, so record_path gives no rows for them; joining onto the list of all users and filling with 0 keeps them. See JSON and JSON Lines.
Exercise 6: Features without the future
Tables customers(id, signup) and payments(customer_id, day, amount). Write a SQL query for "number of payments and total amount in the 30 days before 2026-06-01" per customer, keeping customers without payments.
Answer
SELECT c.id,
COUNT(p.customer_id) AS n_payments_30d,
COALESCE(SUM(p.amount), 0) AS amount_30d
FROM customers c
LEFT JOIN payments p
ON p.customer_id = c.id
AND p.day >= DATE('2026-06-01', '-30 days')
AND p.day < '2026-06-01'
GROUP BY c.id;The date conditions go in the ON clause: in a WHERE clause they would remove the customers without payments. See Relational Databases and SQL.
Exercise 7: Choose a format
Choose a storage format for each and give one reason: (a) a 40 GB table of click events used for training; (b) a 200-row lookup table that product managers edit; (c) a stream of chat messages appended all day; (d) 50,000 product photos with one label each.
Answer
(a) Parquet, partitioned by date: compressed, typed, readable column by column. (b) CSV (with a data dictionary): people can open and edit it. (c) JSON Lines: one record per line, easy to append and stream. (d) a folder of image files plus a manifest (CSV or JSONL with path, label, hash): labels separate from file locations. See Parquet and Arrow and Image, Audio and Video Dataset Layouts.
Exercise 8: Is it still the same dataset?
A colleague says "I only re-exported the data, nothing changed". The new export has the same rows in a different order and one column renamed from Amount to amount. Would a canonical fingerprint of the manifest or table change? Should it?
Answer
A canonical fingerprint that sorts rows ignores the order, but the renamed column changes it, and it should: code that reads Amount would now break. That is a schema change and deserves a new version with a note. See Dataset Versioning and Data Lakes, Object Storage and Manifests.
Exercise 9: May we use it?
A start-up wants to train a commercial model on (a) customer support chats collected under a privacy notice that mentions "improving our service"; (b) a public image dataset under CC BY-NC 4.0; (c) synthetic tabular data generated from its own customer database. List the questions to settle for each.
Answer
(a) Does "improving our service" cover training this model (purpose limitation, lawful basis)? Remove or pseudonymise personal data in the text; retention period; who may access the chats. (b) NC forbids commercial use: not usable without a different licence from the owner. (c) The generator was fitted on personal data, so check that synthetic rows do not reproduce real customers, and that the original data's purpose covers this use. See Public, Licensed and Synthetic Data and Privacy, Consent, Licensing.
Exercise 10: Placeholders and missingness
In the table below, -1, "" and "unknown" all mean missing. Normalise them, then report the share missing per column and the default rate for rows with and without a missing income.
Answer
import numpy as np
import pandas as pd
df = pd.DataFrame({
"age": [34, -1, 45, 29, -1, 52, 41, 38],
"income": ["52000", "", "61000", "unknown", "", "48000", "", "57000"],
"default": [0, 1, 0, 1, 1, 0, 1, 0],
})
df["age"] = df["age"].replace(-1, np.nan)
df["income"] = pd.to_numeric(df["income"].replace(["", "unknown"], np.nan))
print(df.isna().mean().round(3).to_dict())
print(df.groupby(df["income"].isna().rename("income_missing"))["default"].mean()){'age': 0.25, 'income': 0.5, 'default': 0.0}
income_missing
False 0.0
True 1.0
Name: default, dtype: float64
Every applicant without an income defaulted, and none of the others did: in this small table, missingness alone predicts the label perfectly. On real data that is a strong hint of informative missingness (or of a leak, if incomes were deleted after a default). See Missing-Value Analysis.
Exercise 11: Same customer, three rows
["Lan Pham", "lan pham", "Lan Phạm"] with emails ["lan@ex.vn", "LAN@ex.vn", "lan@ex.vn "]. Write the normalised key that makes all three one customer.
Answer
Use the email, normalised: email.strip().lower(). All three become lan@ex.vn. Names are weaker keys (two people can share a name) and need accent removal and whitespace collapsing to match. See Duplicate Detection.
Exercise 12: Robust outliers
For the values : compute the median, the MAD and the robust z-score of 95. Is it flagged at 3.5?
Answer
Sorted: , so the median is . Absolute deviations: , sorted , so . Robust z of 95: , far above 3.5: flagged. See Outlier Detection.
Exercise 13: Agreement by chance
Two annotators label 100 X-rays as normal or abnormal. They agree on 80. Annotator 1 says "abnormal" 30 times, annotator 2 says it 20 times. Compute Cohen's kappa.
Answer
. . : moderate agreement, so the guidelines for "abnormal" need work. See Label Quality.
Exercise 14: Accuracy on rare classes
A defect detector is tested on 2,000 parts, 40 of them defective. It flags 50 parts, of which 30 are defective. Compute accuracy, recall and precision for "defective", and the majority-baseline accuracy.
Answer
True positives 30, false positives 20, false negatives 10, true negatives . Accuracy ; recall ; precision . Always saying "fine" gives an accuracy of , almost the same, with a recall of 0. See Class Distribution.
Exercise 15: One rule set, many columns
Write a configuration-driven range check that reports, for each column, how many values fall outside its allowed range, and run it on the table below.
Answer
import pandas as pd
df = pd.DataFrame({
"humidity_pct": [45, 52, 101, 60, -3],
"temp_c": [21.5, 19.0, 22.1, 88.0, 20.4],
"wind_ms": [3.2, 0.0, 5.1, 2.2, 61.0],
})
RANGES = {"humidity_pct": (0, 100), "temp_c": (-40, 55), "wind_ms": (0, 60)}
for col, (lo, hi) in RANGES.items():
bad = df[col][(df[col] < lo) | (df[col] > hi)]
print(f"{col:13} outside [{lo}, {hi}]: {len(bad)} {bad.tolist()}")humidity_pct outside [0, 100]: 2 [101, -3]
temp_c outside [-40, 55]: 1 [88.0]
wind_ms outside [0, 60]: 1 [61.0]
88 °C is probably a Fahrenheit reading (31 °C), and 61 m/s would be a record-breaking wind: both are worth a question to the data owner rather than a silent fix. The configuration, not the code, holds the judgement calls. See Data Consistency and A Reproducible Data Quality Report.
Test yourself
Which statement about a pandas dtype is true?
int64means the column is a quantity- The dtype says how values are stored, not what they mean
objectcolumns are always text categories- Dates are detected automatically in every CSV
Which mechanism makes the observed values of a column biased so that no imputation from the data alone can fix it?
- MCAR
- MAR
- MNAR
- Duplicates
What must a reproducible quality report contain at the top?
- The time it was generated
- The dataset version (fingerprint), the data's date and the version of the checks
- Every row of the dataset
- The model's accuracy