Skip to content

26. Data cleaning — Exercises

These exercises practice every idea of the data cleaning lesson. They use the course datasets: data/sales_raw.csv, data/customers.csv, data/houses.csv, data/sensors.csv, data/messy_names.txt and the dimension tables data/products.csv and data/stores.csv.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and the starter code into a script and replace each to-do comment with your code.
  3. Run the script. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Every solution ends with assert checks. Keep them in your own version: in data cleaning, an assert that compares a count with the documentation is the cheapest test you can write.

Every exercise runs after this block. It prints nothing.

import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
Warm-up

Load data/customers.csv and data/houses.csv. For each file, print the name of every column that has missing values, with its count and its share of the rows in percent (1 decimal). Use the format shown.

Expected output
data/customers.csv total_charges 10 (0.2%)
data/houses.csv lot_sqft 90 (3.0%)
data/houses.csv school_rating 90 (3.0%)
Starter
for path in ["data/customers.csv", "data/houses.csv"]:
df = pd.read_csv(path)
# TODO: count the gaps per column and keep the columns with gaps
# TODO: print one line per column: path, name, count, percent
Hint 1

df.isna().sum() gives one count per column. Keep the entries greater than 0.

Hint 2

The share is count / len(df) * 100. df.isna().mean() gives the share directly, as a fraction.

Solution
found = {}
for path in ["data/customers.csv", "data/houses.csv"]:
df = pd.read_csv(path)
counts = df.isna().sum()
for column, count in counts[counts > 0].items():
print(f"{path:<20} {column:<15} {count:>3} ({count / len(df):.1%})")
found[column] = count
assert found == {"total_charges": 10, "lot_sqft": 90, "school_rating": 90}
Output
data/customers.csv total_charges 10 (0.2%)
data/houses.csv lot_sqft 90 (3.0%)
data/houses.csv school_rating 90 (3.0%)

How it works:

  1. isna() marks every missing cell. sum() counts the True values per column.
  2. counts[counts > 0] keeps only the columns with gaps. .items() gives (name, count) pairs.
  3. The format spec .1% multiplies by 100 and adds the percent sign.

Alternative: df.isna().mean() returns the share per column directly. (df.isna().mean() * 100).round(1) gives percentages as a Series.

M26-W02 · Predict the output: missing-value rules

Section titled “M26-W02 · Predict the output: missing-value rules”
Warm-up

Predict the output: what does each line print? Write your answers before you run the code.

Starter
s = pd.Series([2.0, np.nan, 4.0])
print((s == np.nan).any())
print(s.isna().sum())
print(s.sum(), s.mean())
print(s.count(), len(s))
print(s.mean(skipna=False))
# TODO: write your prediction for each line, then run the code

Acceptance criteria: Write your prediction line by line, then run the code. Your prediction matches the Output in the solution.

Hint 1

NaN is not equal to anything, including itself.

Hint 2

Reductions such as sum() and mean() skip missing values unless you pass skipna=False. count() counts present values; len() counts rows.

Solution
s = pd.Series([2.0, np.nan, 4.0])
print((s == np.nan).any())
print(s.isna().sum())
print(s.sum(), s.mean())
print(s.count(), len(s))
print(s.mean(skipna=False))
assert not (s == np.nan).any()
assert s.mean() == 3.0
assert len(s) - s.count() == 1
Output
False
1
6.0 3.0
2 3
nan

How it works:

  1. s == np.nan is False everywhere, even at the gap, so .any() is False. This is why you must use isna().
  2. isna().sum() counts the one gap.
  3. sum() adds 2 and 4. mean() divides by the 2 present values, not by 3.
  4. count() is 2 and len() is 3. Their difference is the number of gaps.
  5. With skipna=False, one gap makes the whole result NaN.

M26-W03 · Declare the missing-value tokens

Section titled “M26-W03 · Declare the missing-value tokens”
Warm-up

Load data/sales_raw.csv twice: once with the defaults and once with keep_default_na=False and the tokens "", N/A and -. For each load, print the dtype of discount and its number of gaps.

Expected output
default str gaps: 17
strict float64 gaps: 24
Starter
default = pd.read_csv("data/sales_raw.csv")
# TODO: load again with explicit tokens
# TODO: print the dtype and the gap count of "discount" for both loads
Hint 1

pd.read_csv(path, keep_default_na=False, na_values=["", "N/A", "-"]).

Solution
default = pd.read_csv("data/sales_raw.csv")
strict = pd.read_csv(
"data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"]
)
for name, df in [("default", default), ("strict", strict)]:
dtype, gaps = str(df["discount"].dtype), df["discount"].isna().sum()
print(f"{name:<8} {dtype:<8} gaps: {gaps}")
assert strict["discount"].isna().sum() == 24
assert strict["discount"].dtype == "float64"
Output
default str gaps: 17
strict float64 gaps: 24

How it works:

  1. With the defaults, the 7 dashes stay as text. One text value makes the whole column str, and only 17 cells count as gaps.
  2. With explicit tokens, all 24 gaps are NaN and the rest are numbers, so pandas loads the column as float64.
  3. str(...) turns the dtype into text, so the format spec can pad it.

M26-W04 · Fix the bug: the dollar sign that stays

Section titled “M26-W04 · Fix the bug: the dollar sign that stays”
Warm-up

Fix the bug: this code should turn the price text into numbers, but it raises a ValueError. Find the cause and fix it, then print the dtype, the gap count and the maximum.

Expected output
float64 10 1299.0
Starter
raw = pd.read_csv("data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"])
digits = raw["unit_price"].str.replace("$", "", regex=True).str.replace(",", "")
price = pd.to_numeric(digits) # ValueError: Unable to parse string "$249.00"
# TODO: fix the replace call, then print dtype, gaps and max
Hint 1

With regex=True, the pattern is a regular expression. What does $ mean in a regular expression?

Hint 2

$ is the end-of-text anchor. It matches the empty position at the end, so nothing is removed. Use regex=False, or put the sign in a character class: [$,].

Solution
raw = pd.read_csv(
"data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"]
)
digits = raw["unit_price"].str.replace(r"[$,]", "", regex=True)
price = pd.to_numeric(digits)
print(price.dtype, price.isna().sum(), price.max())
assert price.isna().sum() == raw["unit_price"].isna().sum() == 10
assert price.max() == 1299.0
Output
float64 10 1299.0

How it works:

  1. The character class [$,] matches one character that is either $ or ,. Inside a class, $ is a plain character.
  2. One replace call removes both kinds of junk.
  3. The gap count is the same before and after, so no price failed to convert.

Alternative: two plain-text replacements with regex=False: .str.replace("$", "", regex=False).str.replace(",", "", regex=False).

Warm-up

A web form stores the sales channel as free text. Normalize the values to online and store: strip spaces, use lower case and map the synonym web to online. Keep the gap. Print the counts, with the gap.

Expected output
{'online': 4, 'store': 2, nan: 1}
Starter
channel = pd.Series([" Online", "STORE", "store ", "online", None, "web", "Web "])
# TODO: strip, lower case, map "web" to "online"
# TODO: print value_counts with the gaps
Hint 1

Chain .str.strip().str.lower(), then .replace({"web": "online"}).

Solution
channel = pd.Series([" Online", "STORE", "store ", "online", None, "web", "Web "])
clean = channel.str.strip().str.lower().replace({"web": "online"})
counts = clean.value_counts(dropna=False)
print(counts.to_dict())
assert counts["online"] == 4 and counts["store"] == 2
assert clean.isna().sum() == 1
Output
{'online': 4, 'store': 2, nan: 1}

How it works:

  1. .str.strip() removes the spaces at both ends. .str.lower() makes the case equal.
  2. replace with a dict rewrites whole values. It runs after the normalization, so "Web " has already become "web".
  3. value_counts(dropna=False) shows the gap as its own entry, so you see that it survived.

M26-W06 · Predict the output: duplicated and keep

Section titled “M26-W06 · Predict the output: duplicated and keep”
Warm-up

Predict the output: an order system wrote one order line twice and corrected the discount of another line. What does each line print?

Starter
lines = pd.DataFrame(
{
"order_id": ["O1", "O1", "O2", "O2", "O3"],
"product_id": ["P001", "P001", "P007", "P007", "P001"],
"discount": [0.0, 0.0, 0.0, 0.1, 0.0],
}
)
key = ["order_id", "product_id"]
print(lines.duplicated().tolist())
print(lines.duplicated(subset=key).tolist())
print(lines.duplicated(subset=key, keep="last").tolist())
print(lines.duplicated(subset=key, keep=False).sum())
print(lines.drop_duplicates(subset=key, keep="last")["discount"].tolist())
# TODO: write your prediction for each line, then run the code

Acceptance criteria: Write your prediction line by line, then run the code. Your prediction matches the Output in the solution.

Hint 1

Without subset, all columns must be equal. The two O2 rows differ in discount.

Hint 2

keep="first" leaves the first copy unmarked, keep="last" leaves the last copy unmarked and keep=False marks every copy.

Solution
lines = pd.DataFrame(
{
"order_id": ["O1", "O1", "O2", "O2", "O3"],
"product_id": ["P001", "P001", "P007", "P007", "P001"],
"discount": [0.0, 0.0, 0.0, 0.1, 0.0],
}
)
key = ["order_id", "product_id"]
print(lines.duplicated().tolist())
print(lines.duplicated(subset=key).tolist())
print(lines.duplicated(subset=key, keep="last").tolist())
print(lines.duplicated(subset=key, keep=False).sum())
print(lines.drop_duplicates(subset=key, keep="last")["discount"].tolist())
assert lines.duplicated().sum() == 1
assert lines.duplicated(subset=key).sum() == 2
Output
[False, True, False, False, False]
[False, True, False, True, False]
[True, False, True, False, False]
4
[0.0, 0.1, 0.0]

How it works:

  1. Exact test: only row 1 equals an earlier row in every column. The O2 rows differ in discount.
  2. Key test: rows 1 and 3 repeat an earlier key.
  3. keep="last" marks the earlier copies instead: rows 0 and 2.
  4. keep=False marks all 4 rows that belong to a duplicate group.
  5. Keeping the last copy keeps the corrected discount 0.1 for O2.
Warm-up

A European export writes dates as DD/MM/YYYY. Parse the list below with an explicit format and errors="coerce". Print the parsed dates as ISO text and the number of values that could not be parsed, then print those raw values.

Expected output
['2023-01-07', '2023-01-13', nan, nan, '2024-12-01']
could not parse: 2
['31/02/2024', '2024-03-05']
Starter
raw_dates = pd.Series(["07/01/2023", "13/01/2023", "31/02/2024", "2024-03-05", "01/12/2024"])
# TODO: parse with format="%d/%m/%Y" and errors="coerce"
# TODO: print ISO strings, the NaT count and the raw values that failed
Hint 1

pd.to_datetime(raw_dates, format="%d/%m/%Y", errors="coerce") gives NaT for every value that does not fit.

Hint 2

.dt.strftime("%Y-%m-%d") formats the dates as text. raw_dates[parsed.isna()] selects the values that failed.

Solution
raw_dates = pd.Series(
["07/01/2023", "13/01/2023", "31/02/2024", "2024-03-05", "01/12/2024"]
)
parsed = pd.to_datetime(raw_dates, format="%d/%m/%Y", errors="coerce")
print(parsed.dt.strftime("%Y-%m-%d").tolist())
print("could not parse:", parsed.isna().sum())
print(raw_dates[parsed.isna()].tolist())
assert parsed.isna().sum() == 2
assert parsed.iloc[0] == pd.Timestamp("2023-01-07")
Output
['2023-01-07', '2023-01-13', nan, nan, '2024-12-01']
could not parse: 2
['31/02/2024', '2024-03-05']

How it works:

  1. The explicit format reads the day first, so 07/01/2023 becomes 7 January.
  2. 31/02/2024 fits the pattern but is not a real date (February has no 31st). 2024-03-05 has another format. Both become NaT.
  3. strftime turns NaT into NaN, which tolist() shows as nan.
  4. Listing the failures tells you what to do next: the ISO value needs a second format; the impossible date needs a human.
Warm-up

Compute the IQR fences for sqft in data/houses.csv. Print Q1, Q3, the IQR, both fences and the number of houses outside the fences.

Expected output
Q1 1350 | Q3 2210 | IQR 860
fences 60 to 3500 | outside: 88
Starter
sqft = pd.read_csv("data/houses.csv")["sqft"]
# TODO: Q1, Q3 and IQR
# TODO: lower and upper fence, number of houses outside
Hint 1

q1, q3 = sqft.quantile([0.25, 0.75]) unpacks both quartiles.

Hint 2

The fences are q1 - 1.5 * iqr and q3 + 1.5 * iqr. ~sqft.between(lower, upper) marks the houses outside.

Solution
sqft = pd.read_csv("data/houses.csv")["sqft"]
q1, q3 = sqft.quantile([0.25, 0.75])
iqr = q3 - q1
lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr
outside = ~sqft.between(lower, upper)
print(f"Q1 {q1:.0f} | Q3 {q3:.0f} | IQR {iqr:.0f}")
print(f"fences {lower:.0f} to {upper:.0f} | outside: {outside.sum()}")
assert outside.sum() == ((sqft < lower) | (sqft > upper)).sum()
assert lower < sqft.median() < upper
Output
Q1 1350 | Q3 2210 | IQR 860
fences 60 to 3500 | outside: 88

How it works:

  1. The quartiles cut the sorted values into quarters. The IQR is the width of the middle half.
  2. The fences lie 1.5 IQR below Q1 and above Q3.
  3. between includes both ends, so ~between is exactly “below the lower or above the upper fence”.
  4. The lower fence is below the smallest house (550 sq ft), so every flagged house is a large one. Large houses are rare but real: this is a list to inspect, not to delete.

M26-W09 · Fill with the median and keep an indicator

Section titled “M26-W09 · Fill with the median and keep an indicator”
Warm-up

Fill the gaps of school_rating in data/houses.csv with the median rating. First add a column school_rating_missing that records which values were missing. Print the median used, the number of flagged rows and the gaps left.

Expected output
median: 6.0
flagged: 90
gaps left: 0
Starter
houses = pd.read_csv("data/houses.csv")
# TODO: add the indicator column first
# TODO: fill with the median, print median, flagged rows and gaps left
Hint 1

Create the indicator before the fill: after the fill, isna() finds nothing.

Solution
houses = pd.read_csv("data/houses.csv")
houses["school_rating_missing"] = houses["school_rating"].isna()
median = houses["school_rating"].median()
houses["school_rating"] = houses["school_rating"].fillna(median)
print("median:", median)
print("flagged:", houses["school_rating_missing"].sum())
print("gaps left:", houses["school_rating"].isna().sum())
assert houses["school_rating_missing"].sum() == 90
assert houses["school_rating"].isna().sum() == 0
Output
median: 6.0
flagged: 90
gaps left: 0

How it works:

  1. The indicator is a copy of the gap mask, saved as a column. It must come first.
  2. median() skips the gaps, so it is the median of the 2,910 known ratings.
  3. fillna(median) replaces each gap with that one number.

Alternative: a group-wise median, houses.groupby("neighborhood")["school_rating"].transform("median"), gives each house the median of its own neighborhood. Exercise M26-C03 does this.

Core

A missingness pattern is the combination of columns that are missing together in a row. For data/houses.csv, count how many rows have each combination of gaps in lot_sqft and school_rating. Then print the share of rows that are complete.

Expected output
lot_sqft school_rating
False False 2821
True 89
True False 89
True 1
Name: count, dtype: int64
complete rows: 94.0%
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["lot_sqft", "school_rating"]
# TODO: count the rows per combination of isna() values
# TODO: print the share of complete rows
Hint 1

houses[cols].isna() is a table of True/False. value_counts() on a DataFrame counts each distinct row.

Hint 2

A row is complete when notna().all(axis=1) is True. Its .mean() is the share.

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["lot_sqft", "school_rating"]
patterns = houses[cols].isna().value_counts()
print(patterns)
complete = houses[cols].notna().all(axis=1)
print(f"complete rows: {complete.mean():.1%}")
assert patterns.sum() == len(houses)
assert patterns[(True, True)] == 1
Output
lot_sqft school_rating
False False 2821
True 89
True False 89
True 1
Name: count, dtype: int64
complete rows: 94.0%

How it works:

  1. isna() turns each row into a pattern such as (False, True): rating missing, lot known.
  2. value_counts() on the two-column table counts each pattern. The index is a pair of booleans.
  3. Only 1 row misses both values. If the gaps were linked, for example because one survey page was skipped, the (True, True) row would be large.
  4. notna().all(axis=1) is True for rows with no gap in any of the columns.

M26-C02 · Interpret a result: are the gaps random?

Section titled “M26-C02 · Interpret a result: are the gaps random?”
Core

Interpret a result: compare the houses with a missing lot_sqft with the houses that have a value. Print the mean sqft, distance_to_center_km and price for both groups. Then run a permutation check: shuffle the gap mask 1,000 times (np.random.default_rng(42)) and print, per column, the share of shuffles whose mean difference is at least as large as the real one. Answer: does the evidence fit MCAR, and is dropping these rows safe?

Expected output
sqft distance_to_center_km price
lot_missing
False 1856.4 8.6 475960.8
True 1863.4 8.1 492783.3
{'sqft': 0.921, 'distance_to_center_km': 0.432, 'price': 0.61}
Starter
houses = pd.read_csv("data/houses.csv")
rng = np.random.default_rng(42)
# TODO: group by houses["lot_sqft"].isna() and compute the three means
# TODO: permutation check per column: share of 1,000 shuffles at least as extreme
# TODO: print the results, then write your interpretation as a comment
Hint 1

houses.groupby(houses["lot_sqft"].isna())[cols].mean() puts the two groups side by side.

Hint 2

Under MCAR, the two groups differ only by chance. rng.permutation(mask) puts the same number of gaps on random rows. Compute the difference of means for each shuffle, and compare the real difference with these chance differences.

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "distance_to_center_km", "price"]
table = houses.groupby(houses["lot_sqft"].isna().rename("lot_missing"))[cols].mean()
print(table.round(1))
rng = np.random.default_rng(42)
gap = houses["lot_sqft"].isna().to_numpy()
p_values = {}
for c in cols:
x = houses[c].to_numpy()
observed = x[gap].mean() - x[~gap].mean()
chance = []
for _ in range(1000):
m = rng.permutation(gap)
chance.append(x[m].mean() - x[~m].mean())
p_values[c] = float((np.abs(chance) >= abs(observed)).mean())
print(p_values)
assert set(table.index) == {False, True}
assert min(p_values.values()) > 0.05
Output
sqft distance_to_center_km price
lot_missing
False 1856.4 8.6 475960.8
True 1863.4 8.1 492783.3
{'sqft': 0.921, 'distance_to_center_km': 0.432, 'price': 0.61}

How it works:

  1. The groupby key is the gap mask, renamed to lot_missing so the table is readable.
  2. The permutation loop moves the 90 gaps to random houses 1,000 times. Each shuffle gives a difference that chance alone produces.
  3. The printed share is the fraction of shuffles with a difference at least as large as the real one (a p-value, module 29). All three shares are far above 0.05: differences of this size happen by chance most of the time. Nothing points to a link between the gaps and size, location or price.

Interpretation: the evidence is consistent with MCAR. It cannot prove MCAR: the gaps could still depend on something the table does not record. Dropping the 90 rows is unbiased, but it wastes the other 13 columns of those houses. A neighborhood-median fill with an indicator column keeps them. If the gap group had been, say, 40% farther from the center, the gaps would be MAR, and dropping would remove large-lot houses on purpose.

M26-C03 · Group-wise median fill with a nullable integer

Section titled “M26-C03 · Group-wise median fill with a nullable integer”
Core

school_rating is a whole number from 1 to 10. Fill its gaps with the median rating of the house’s neighborhood, round the result, and store the column as the nullable integer dtype Int64. Print the number of filled values per neighborhood, the final dtype and the range of the column.

Expected output
neighborhood
Cedar Park 10
Downtown 11
Lakeview 6
Maple Grove 17
Oak Hill 12
Old Town 10
Riverside 10
Westfield 14
Name: count, dtype: int64
Int64 1 10 0
Starter
houses = pd.read_csv("data/houses.csv")
gap = houses["school_rating"].isna()
# TODO: neighborhood median with groupby + transform
# TODO: fill, round, astype("Int64")
# TODO: print filled counts per neighborhood, dtype and min/max
Hint 1

houses.groupby("neighborhood")["school_rating"].transform("median") returns one median per row, aligned with the table.

Hint 2

A median of an even number of values can end in .5. Round before you cast: .round().astype("Int64").

Solution
houses = pd.read_csv("data/houses.csv")
gap = houses["school_rating"].isna()
area_median = houses.groupby("neighborhood")["school_rating"].transform("median")
houses["school_rating"] = (
houses["school_rating"].fillna(area_median).round().astype("Int64")
)
print(houses.loc[gap, "neighborhood"].value_counts().sort_index())
rating = houses["school_rating"]
print(rating.dtype, rating.min(), rating.max(), rating.isna().sum())
assert rating.dtype == "Int64"
assert rating.between(1, 10).all()
Output
neighborhood
Cedar Park 10
Downtown 11
Lakeview 6
Maple Grove 17
Oak Hill 12
Old Town 10
Riverside 10
Westfield 14
Name: count, dtype: int64
Int64 1 10 0

How it works:

  1. transform("median") computes the median per neighborhood and broadcasts it back to every row of that neighborhood.
  2. fillna uses that per-row value only where the rating is missing.
  3. round() turns a median such as 6.5 into a whole number. Python and pandas round halves to the even number (module 01), so 6.5 becomes 6.
  4. Int64 stores whole numbers and would keep any remaining gap as pd.NA. float64 would show 7.0 instead of 7.

M26-C04 · Choose a method and justify it: new customers

Section titled “M26-C04 · Choose a method and justify it: new customers”
Core

Choose a method and justify it: total_charges in data/customers.csv has 10 gaps. Look at those rows, choose a fill, apply it, and check the result with the rule from the data dictionary: total_charges is about monthly_charges × tenure_months (within 6%). Print the evidence, then the share of all customers who satisfy the rule after the fill.

Expected output
tenure: [0] | signup months: ['2024-12']
rule holds for 99.98% of customers
Starter
customers = pd.read_csv("data/customers.csv")
gap = customers["total_charges"].isna()
# TODO: print the tenure and signup months of the gap rows
# TODO: choose and apply the fill; justify it in a comment
# TODO: check the rule |total - monthly * tenure| <= 6% of monthly * tenure
Hint 1

Print customers.loc[gap, ["tenure_months", "signup_date"]]. What is the total of a customer who has not been billed yet?

Hint 2

For a tenure of 0, the expected total is 0, so a 6% tolerance means “exactly 0”. Use np.isclose(total, expected, rtol=0.06, atol=0.01).

Solution
customers = pd.read_csv("data/customers.csv")
gap = customers["total_charges"].isna()
evidence = customers.loc[gap, ["tenure_months", "signup_date"]]
months = evidence["signup_date"].str[:7].unique().tolist()
tenure = evidence["tenure_months"].unique().tolist()
print("tenure:", tenure, "| signup months:", months)
# Structural gap: 0 months of tenure means nothing has been billed yet.
customers["total_charges"] = customers["total_charges"].fillna(0.0)
expected = customers["monthly_charges"] * customers["tenure_months"]
ok = np.isclose(customers["total_charges"], expected, rtol=0.06, atol=0.01)
print(f"rule holds for {ok.mean():.2%} of customers")
assert ok[gap].all()
assert customers["total_charges"].isna().sum() == 0
Output
tenure: [0] | signup months: ['2024-12']
rule holds for 99.98% of customers

How it works:

  1. All gap rows have a tenure of 0 and signed up in December 2024. That is a structural gap: the value is 0 by definition, not unknown.
  2. fillna(0.0) applies the rule. The mean, about 1,386 USD, would invent charges for customers who never paid.
  3. np.isclose with rtol=0.06 checks the documented relationship. atol=0.01 handles the expected value 0, where a relative tolerance alone would demand exact equality.
  4. The rule holds for 99.98% of the customers: one old record lies just outside the 6% band, ordinary noise. All 10 filled rows satisfy it (the first assert). A mean fill would break the rule on exactly those 10 rows.
Core

An order system logs every edit of an order line as a new row with an updated_at time. Keep only the latest version of each (order_id, product_id) line. Print the number of rows before and after, and the final table sorted by order_id.

Expected output
5 -> 3
order_id product_id quantity discount updated_at
1 O000051 P001 1 0.05 2023-01-04 09:00:00
3 O000051 P029 4 0.00 2023-01-04 17:30:00
4 O000062 P028 2 0.00 2023-01-06 08:15:00
Starter
edits = pd.DataFrame(
{
"order_id": ["O000051", "O000051", "O000062", "O000051", "O000062"],
"product_id": ["P029", "P001", "P028", "P029", "P028"],
"quantity": [4, 1, 1, 4, 2],
"discount": [np.nan, 0.05, 0.0, 0.0, 0.0],
"updated_at": pd.to_datetime(
["2023-01-04 09:00", "2023-01-04 09:00", "2023-01-05 10:00",
"2023-01-04 17:30", "2023-01-06 08:15"]
),
}
)
# TODO: sort by updated_at, then drop duplicates by key keeping the last
Hint 1

drop_duplicates(keep="last") keeps the last row in table order. Make sure the table order is time order first.

Hint 2

Sort by the time column first, then use drop_duplicates with subset and keep="last".

Solution
edits = pd.DataFrame(
{
"order_id": ["O000051", "O000051", "O000062", "O000051", "O000062"],
"product_id": ["P029", "P001", "P028", "P029", "P028"],
"quantity": [4, 1, 1, 4, 2],
"discount": [np.nan, 0.05, 0.0, 0.0, 0.0],
"updated_at": pd.to_datetime(
[
"2023-01-04 09:00",
"2023-01-04 09:00",
"2023-01-05 10:00",
"2023-01-04 17:30",
"2023-01-06 08:15",
]
),
}
)
key = ["order_id", "product_id"]
latest = (
edits.sort_values("updated_at")
.drop_duplicates(subset=key, keep="last")
.sort_values(key)
)
print(len(edits), "->", len(latest))
print(latest)
assert not latest.duplicated(subset=key).any()
assert latest.loc[latest["order_id"] == "O000062", "quantity"].item() == 2
Output
5 -> 3
order_id product_id quantity discount updated_at
1 O000051 P001 1 0.05 2023-01-04 09:00:00
3 O000051 P029 4 0.00 2023-01-04 17:30:00
4 O000062 P028 2 0.00 2023-01-06 08:15:00

How it works:

  1. sort_values("updated_at") puts every edit in time order.
  2. drop_duplicates(subset=key, keep="last") keeps the newest row per key. The P029 line keeps its corrected discount 0.0 instead of the gap.
  3. The final sort_values(key) only makes the output easy to read.
  4. The index labels show which original rows survived: 1, 3 and 4.

Alternative: edits.loc[edits.groupby(key)["updated_at"].idxmax()] picks the row with the latest time per group, with no sorting step.

Core

data/messy_names.txt holds 20 customer names with odd spaces, case and accents. Two lines use the decomposed Unicode form NFD (module 02), so they look equal to other lines but are not. Normalize the names (strip, collapse spaces, title case, NFC) and print the duplicate groups that appear.

Expected output
duplicates: 0 -> 2
line 1: 'José García' (raw ' josé GARCÍA ')
line 8: 'José García' (raw 'José García')
line 2: "Zoë O'Brien" (raw "ZOË o'brien")
line 13: "Zoë O'Brien" (raw "Zoë O'Brien")
Starter
from pathlib import Path
names = pd.Series(Path("data/messy_names.txt").read_text(encoding="utf-8").splitlines())
# TODO: normalize the names with the .str accessor
# TODO: print every name that belongs to a duplicate group, with its line number
Hint 1

The .str accessor has normalize("NFC"), which joins a letter and its combining accent into one character.

Hint 2

clean.duplicated(keep=False) marks every member of a group. Line numbers are the index plus 1.

Solution
from pathlib import Path
text = Path("data/messy_names.txt").read_text(encoding="utf-8")
names = pd.Series(text.splitlines())
clean = (
names.str.normalize("NFC")
.str.strip()
.str.replace(r"\s+", " ", regex=True)
.str.title()
)
print("duplicates:", names.duplicated().sum(), "->", clean.duplicated().sum())
groups = clean[clean.duplicated(keep=False)]
for line, name in groups.sort_values().items():
print(f"line {line + 1:>2}: {name!r} (raw {names[line]!r})")
assert clean.duplicated().sum() == 2
Output
duplicates: 0 -> 2
line 1: 'José García' (raw ' josé GARCÍA ')
line 8: 'José García' (raw 'José García')
line 2: "Zoë O'Brien" (raw "ZOË o'brien")
line 13: "Zoë O'Brien" (raw "Zoë O'Brien")

How it works:

  1. normalize("NFC") turns the decomposed e + accent into one é, so equal-looking names become equal strings.
  2. strip, the \s+ replacement and title remove the spacing and case differences.
  3. After normalization, lines 1 and 8 and lines 2 and 13 are the same person. Before it, == saw no duplicate at all.
  4. title() capitalizes after the apostrophe, so o'brien becomes O'Brien. It is a reasonable rule here, but it would turn McDonald into Mcdonald: check title case on your own names.

M26-C07 · Fix the bug: dates that parse but lie

Section titled “M26-C07 · Fix the bug: dates that parse but lie”
Core

Fix the bug: this code parses every order_date of data/sales_raw.csv with no NaT, so it looks correct. Prove that it is wrong with the rule “dates never fall when order_id rises”, then fix it and prove the fix. Print the result of the check before and after, and the number of dates that change.

Expected output
quick parse: False | explicit parse: True
dates that change: 269 | NaT: 0
Starter
raw = pd.read_csv("data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"])
dates = pd.to_datetime(raw["order_date"], format="mixed", dayfirst=True)
print(dates.isna().sum()) # 0: looks fine
# TODO: write rises_with_id(dates) using the earliest date per order_id
# TODO: parse the three formats explicitly and check again
Hint 1

dates.groupby(raw["order_id"]).min().sort_index().is_monotonic_increasing is True only when no later order has an earlier date.

Hint 2

The three formats are %Y-%m-%d, %d/%m/%Y and %B %d, %Y. Parse each with errors="coerce" and join them with combine_first.

Solution
raw = pd.read_csv(
"data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"]
)
def rises_with_id(dates: pd.Series) -> bool:
return dates.groupby(raw["order_id"]).min().sort_index().is_monotonic_increasing
quick = pd.to_datetime(raw["order_date"], format="mixed", dayfirst=True)
fixed = None
for fmt in ["%Y-%m-%d", "%d/%m/%Y", "%B %d, %Y"]:
part = pd.to_datetime(raw["order_date"], format=fmt, errors="coerce")
fixed = part if fixed is None else fixed.combine_first(part)
print("quick parse:", rises_with_id(quick), "| explicit parse:", rises_with_id(fixed))
print("dates that change:", (quick != fixed).sum(), "| NaT:", fixed.isna().sum())
assert rises_with_id(fixed) and not rises_with_id(quick)
assert fixed.isna().sum() == 0
Output
quick parse: False | explicit parse: True
dates that change: 269 | NaT: 0

How it works:

  1. rises_with_id takes the earliest date of each order and checks that the sequence never goes down when the order ids are sorted.
  2. The quick parse fails the check: with dayfirst=True, pandas reads ISO dates such as 2023-01-04 as 1 April.
  3. The loop parses each format strictly and fills the gaps of the result from the next format.
  4. 269 dates change, and the check passes. A parse with no NaT is not proof of a correct parse; a rule from another column is.

M26-C08 · Refactor a row loop into vectorized code

Section titled “M26-C08 · Refactor a row loop into vectorized code”
Core

Refactor: the function below cleans the unit_price text one row at a time. Rewrite it with vectorized .str and pd.to_numeric calls, with no Python loop. Check that both versions give the same Series, and print the gap count and the mean price.

Expected output
gaps: 10 | mean: 139.65
Starter
raw = pd.read_csv("data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"])
def clean_prices_loop(prices: pd.Series) -> pd.Series:
values = []
for p in prices:
if pd.isna(p):
values.append(np.nan)
else:
values.append(float(p.strip().lstrip("$").replace(",", "")))
return pd.Series(values, index=prices.index, name=prices.name)
# TODO: write clean_prices_vectorized(prices) with no loop
Hint 1

.str.strip() and .str.replace(r"[$,]", "", regex=True) work on the whole column and skip the gaps.

Hint 2

pd.testing.assert_series_equal(a, b) raises an AssertionError with a clear message if two Series differ.

Solution
raw = pd.read_csv(
"data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"]
)
def clean_prices_loop(prices: pd.Series) -> pd.Series:
values = []
for p in prices:
if pd.isna(p):
values.append(np.nan)
else:
values.append(float(p.strip().lstrip("$").replace(",", "")))
return pd.Series(values, index=prices.index, name=prices.name)
def clean_prices_vectorized(prices: pd.Series) -> pd.Series:
digits = prices.str.strip().str.replace(r"[$,]", "", regex=True)
return pd.to_numeric(digits, errors="coerce")
loop = clean_prices_loop(raw["unit_price"])
fast = clean_prices_vectorized(raw["unit_price"])
pd.testing.assert_series_equal(loop, fast)
print("gaps:", fast.isna().sum(), "| mean:", round(fast.mean(), 2))
assert fast.isna().sum() == 10
assert fast.dtype == "float64"
Output
gaps: 10 | mean: 139.65

How it works:

  1. The vectorized version runs each string operation once over the whole column. The gaps pass through .str methods untouched.
  2. pd.to_numeric(..., errors="coerce") replaces the float() call and the isna branch at once.
  3. assert_series_equal compares values, dtype, index and name, so the refactor is proven equal.
  4. There is one difference in behavior: on a value such as "n/a", the loop raises a ValueError and the vectorized version gives NaN. Count the gaps after the conversion to catch it.

M26-C09 · Score interpolation and forward fill on humidity

Section titled “M26-C09 · Score interpolation and forward fill on humidity”
Core

Hide 300 known humidity_pct values of data/sensors.csv (use np.random.default_rng(42)). Fill them per sensor with forward fill and with linear interpolation, and print the MAE of each method. Then fill the real gaps with the better method and print the gaps left.

Expected output
ffill MAE 0.601
interpolate MAE 0.391
gaps left: 0
Starter
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
rng = np.random.default_rng(42)
col = "humidity_pct"
# TODO: hide 300 known values in a copy
# TODO: ffill and interpolate per sensor, print the MAE of each
# TODO: fill the real gaps with the better method
Hint 1

known = sensors.index[sensors[col].notna()] and rng.choice(known, size=300, replace=False) pick the rows to hide.

Hint 2

Group by sensor_id before you fill. A grouped column has an ffill() method; for interpolation, use transform with a function that calls interpolate().

Solution
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
rng = np.random.default_rng(42)
col = "humidity_pct"
known = sensors.index[sensors[col].notna()]
hidden = rng.choice(known, size=300, replace=False)
test = sensors.copy()
test.loc[hidden, col] = np.nan
by_sensor = test.groupby("sensor_id")[col]
scores = {
"ffill": by_sensor.ffill(),
"interpolate": by_sensor.transform(lambda s: s.interpolate()),
}
truth = sensors.loc[hidden, col]
mae = {name: (filled[hidden] - truth).abs().mean() for name, filled in scores.items()}
for name, value in mae.items():
print(f"{name:<12} MAE {value:.3f}")
sensors[col] = sensors.groupby("sensor_id")[col].transform(
lambda s: s.interpolate(limit_direction="both")
)
print("gaps left:", sensors[col].isna().sum())
assert mae["interpolate"] < mae["ffill"]
assert sensors[col].isna().sum() == 0
Output
ffill MAE 0.601
interpolate MAE 0.391
gaps left: 0

How it works:

  1. The hidden values have a known truth, so the error of each method can be measured.
  2. Both fills run per sensor, so a gap never borrows a value from another sensor.
  3. Interpolation uses the value after the gap too, so it follows the curve better than forward fill. That is fine for cleaning history in a batch. In a forecast or a live alert, the value after the gap does not exist yet, so only forward fill is honest there.
  4. limit_direction="both" also fills a gap at the very start or end of a sensor’s series.

M26-C10 · Compare outlier rules on the house prices

Section titled “M26-C10 · Compare outlier rules on the house prices”
Core

For price in data/houses.csv, compare four rules: IQR on the price, z-score > 3 on the price, IQR on the log price and robust z-score > 3.5 on the log price. For each rule, print the number of flagged houses and the number of the 8 injected errors it finds.

Expected output
IQR on price flagged 198 | injected 2
z on price flagged 68 | injected 1
IQR on log price flagged 44 | injected 1
robust z on log flagged 7 | injected 1
Starter
houses = pd.read_csv("data/houses.csv")
injected = ["H0537", "H0542", "H0751", "H0914", "H2277", "H0887", "H0957", "H1990"]
is_injected = houses["house_id"].isin(injected)
# TODO: write iqr_flag(s) and z_flag(s, limit) and robust_flag(s, limit)
# TODO: apply them to price and to np.log(price), print counts
Hint 1

The robust z-score is 0.6745 * (s - s.median()) / mad, where mad = (s - s.median()).abs().median().

Hint 2

Put the four flags in a dict {name: flag} and loop over it to print the counts.

Solution
houses = pd.read_csv("data/houses.csv")
injected = ["H0537", "H0542", "H0751", "H0914", "H2277", "H0887", "H0957", "H1990"]
is_injected = houses["house_id"].isin(injected)
def iqr_flag(s: pd.Series, k: float = 1.5) -> pd.Series:
q1, q3 = s.quantile([0.25, 0.75])
return ~s.between(q1 - k * (q3 - q1), q3 + k * (q3 - q1))
def z_flag(s: pd.Series, limit: float = 3.0) -> pd.Series:
return ((s - s.mean()) / s.std()).abs() > limit
def robust_flag(s: pd.Series, limit: float = 3.5) -> pd.Series:
mad = (s - s.median()).abs().median()
return (0.6745 * (s - s.median()) / mad).abs() > limit
price, log_price = houses["price"], np.log(houses["price"])
flags = {
"IQR on price": iqr_flag(price),
"z on price": z_flag(price),
"IQR on log price": iqr_flag(log_price),
"robust z on log": robust_flag(log_price),
}
for name, flag in flags.items():
print(f"{name:<18} flagged {flag.sum():>4} | injected {(flag & is_injected).sum()}")
assert flags["IQR on price"].sum() > flags["IQR on log price"].sum()
Output
IQR on price flagged 198 | injected 2
z on price flagged 68 | injected 1
IQR on log price flagged 44 | injected 1
robust z on log flagged 7 | injected 1

How it works:

  1. Each function returns a boolean mask, so the rules are easy to compare and combine.
  2. On the raw price, both rules flag the expensive tail, and the z-score flags fewer because the tail inflates the standard deviation.
  3. The log compresses the tail, so the rules on the log price flag far fewer houses.
  4. No global rule finds more than 2 of the 8 errors: they are unusual only for their size and neighborhood. The lesson’s Example 8 adds that context.

M26-C11 · Check referential integrity with a merge indicator

Section titled “M26-C11 · Check referential integrity with a merge indicator”
Core

A partner sends five extra order lines. Check each foreign key (store_id against data/stores.csv, product_id against data/products.csv) with merge(..., how="left", indicator=True). Print the merge status counts for each key and the orphan lines.

Expected output
store_id {'both': 3, 'left_only': 2, 'right_only': 0}
product_id {'both': 4, 'left_only': 1, 'right_only': 0}
{'store_id': ['X002', 'X005'], 'product_id': ['X003']}
Starter
stores = pd.read_csv("data/stores.csv")
products = pd.read_csv("data/products.csv")
extra = pd.DataFrame(
{
"order_id": ["X001", "X002", "X003", "X004", "X005"],
"store_id": ["S01", "S13", "S07", "S07", "s02"],
"product_id": ["P001", "P003", "P031", "P010", "P022"],
}
)
# TODO: merge with each dimension table, indicator=True
# TODO: print the _merge counts and the orphan rows
Hint 1

Merge only the key column of the dimension table, stores[["store_id"]], so the result keeps the shape of extra.

Hint 2

The _merge column is left_only for a line whose key has no match.

Solution
stores = pd.read_csv("data/stores.csv")
products = pd.read_csv("data/products.csv")
extra = pd.DataFrame(
{
"order_id": ["X001", "X002", "X003", "X004", "X005"],
"store_id": ["S01", "S13", "S07", "S07", "s02"],
"product_id": ["P001", "P003", "P031", "P010", "P022"],
}
)
orphans = {}
for key, dim in [("store_id", stores), ("product_id", products)]:
checked = extra.merge(dim[[key]], on=key, how="left", indicator=True)
print(key, checked["_merge"].value_counts().to_dict())
orphans[key] = checked.loc[checked["_merge"] == "left_only", "order_id"].tolist()
print(orphans)
assert orphans == {"store_id": ["X002", "X005"], "product_id": ["X003"]}
Output
store_id {'both': 3, 'left_only': 2, 'right_only': 0}
product_id {'both': 4, 'left_only': 1, 'right_only': 0}
{'store_id': ['X002', 'X005'], 'product_id': ['X003']}

How it works:

  1. A left merge keeps every line of extra. indicator=True adds _merge with both or left_only.
  2. S13 and P031 do not exist, so their lines are orphans.
  3. s02 is an orphan too: the store exists as S02, but keys are case-sensitive. A normalization step (.str.upper()) would fix that line; the other two need the partner to correct their data.
  4. value_counts() also lists right_only with 0, because the column is a categorical with three possible values.

Alternative: ~extra["store_id"].isin(stores["store_id"]) gives the same orphan mask in one line. The merge version is useful when you also want columns from the dimension table.

M26-C12 · Write a validation function for houses

Section titled “M26-C12 · Write a validation function for houses”
Core

Write validate_houses(df) -> list[str] for data/houses.csv with these rules: house_id is unique; no gaps in lot_sqft or school_rating; bedrooms from 1 to 7; bathrooms in steps of 0.5; school_rating from 1 to 10; year_built before the sale year; price greater than 0. Run it on the raw file, then on a copy with the gaps filled by the neighborhood median.

Expected output
['lot_sqft: 90 missing', 'school_rating: 90 missing']
[]
Starter
houses = pd.read_csv("data/houses.csv")
def validate_houses(df: pd.DataFrame) -> list[str]:
problems = []
# TODO: one check per rule; append a short message when a rule fails
return problems
# TODO: print the messages for the raw table and for the filled copy
Hint 1

“Steps of 0.5” means that bathrooms * 2 is a whole number: (df["bathrooms"] * 2 % 1 == 0).all().

Hint 2

The sale year is pd.to_datetime(df["sold_date"]).dt.year. Note that between returns False for gaps, so a range check also fails on missing values.

Solution
houses = pd.read_csv("data/houses.csv")
def validate_houses(df: pd.DataFrame) -> list[str]:
problems = []
if df["house_id"].duplicated().any():
problems.append("house_id: duplicates")
for c in ["lot_sqft", "school_rating"]:
if df[c].isna().any():
problems.append(f"{c}: {df[c].isna().sum()} missing")
if not df["bedrooms"].between(1, 7).all():
problems.append("bedrooms: outside 1..7")
if not (df["bathrooms"] * 2 % 1 == 0).all():
problems.append("bathrooms: not a multiple of 0.5")
if not df["school_rating"].dropna().between(1, 10).all():
problems.append("school_rating: outside 1..10")
sale_year = pd.to_datetime(df["sold_date"], format="%Y-%m-%d").dt.year
if not (df["year_built"] < sale_year).all():
problems.append("year_built: not before the sale year")
if not (df["price"] > 0).all():
problems.append("price: not positive")
return problems
print(validate_houses(houses))
filled = houses.copy()
for c in ["lot_sqft", "school_rating"]:
area_median = filled.groupby("neighborhood")[c].transform("median")
filled[c] = filled[c].fillna(area_median)
print(validate_houses(filled))
assert len(validate_houses(houses)) == 2
assert validate_houses(filled) == []
Output
['lot_sqft: 90 missing', 'school_rating: 90 missing']
[]

How it works:

  1. Each rule is one if that appends a message. The function never stops early, so you see all problems at once.
  2. The range check on school_rating uses dropna(), so a gap is reported once, by the missing-value rule, and not twice.
  3. bathrooms * 2 % 1 == 0 is True for 1.0, 1.5, 2.0 and so on. The values are exact halves in binary, so the float test is safe here.
  4. On the raw table, only the two gap rules fail. After the fill, the list is empty.

M26-C13 · Interpret a result: imputation and correlation

Section titled “M26-C13 · Interpret a result: imputation and correlation”
Core

Interpret a result: lot size grows with the distance to the center. Print the correlation between lot_sqft and distance_to_center_km for three versions of lot_sqft: the observed values only, a global-mean fill and a neighborhood-median fill. Explain the direction of each change.

Expected output
observed only r = 0.730
global mean fill r = 0.719
neighborhood median fill r = 0.734
Starter
houses = pd.read_csv("data/houses.csv")
lot, distance = houses["lot_sqft"], houses["distance_to_center_km"]
# TODO: three versions of lot_sqft
# TODO: print the correlation of each with distance (3 decimals)
Hint 1

a.corr(b) computes the Pearson correlation and skips the rows where either value is missing.

Solution
houses = pd.read_csv("data/houses.csv")
lot, distance = houses["lot_sqft"], houses["distance_to_center_km"]
versions = {
"observed only": lot,
"global mean fill": lot.fillna(lot.mean()),
"neighborhood median fill": lot.fillna(
houses.groupby("neighborhood")["lot_sqft"].transform("median")
),
}
corr = {name: v.corr(distance) for name, v in versions.items()}
for name, value in corr.items():
print(f"{name:<26} r = {value:.3f}")
assert corr["global mean fill"] < corr["observed only"]
Output
observed only r = 0.730
global mean fill r = 0.719
neighborhood median fill r = 0.734

How it works:

  1. The observed correlation uses the 2,910 houses with a value.
  2. The global-mean fill gives 90 houses the same lot size whatever their distance. Those points sit on a flat line, so they weaken the correlation.
  3. The neighborhood-median fill gives a near house a small lot and a far house a large one, because neighborhoods differ in distance. The filled points follow the trend, so the correlation stays the same or even rises a little.

Interpretation: a global fill biases relationships toward zero. A group-wise fill keeps them, but it can also make them look a little stronger than they are, because every filled value sits exactly on its group’s center. Report which fill you used, and keep the indicator column.

M26-X01 · A decorator that logs each cleaning step

Section titled “M26-X01 · A decorator that logs each cleaning step”
Challenge

Write a decorator @logged_step (module 11) for cleaning functions that take a DataFrame and return a DataFrame. It appends a record to a list LOG: the step name, the rows before and after, and the number of cells that changed (compare only rows and columns present in both frames; count a gap that stays a gap as unchanged). Use it on three steps for data/sales_raw.csv: drop exact duplicates, normalize region, and convert unit_price. Print the log as a table.

Expected output
step rows_in rows_out cells_changed
drop_exact_duplicates 1200 1164 0
normalize_region 1164 1164 250
price_to_float 1164 1164 1155
Starter
import functools
from collections.abc import Callable
LOG: list[dict] = []
def logged_step(func: Callable[[pd.DataFrame], pd.DataFrame]):
# TODO: wrap func, measure rows before and after and changed cells
...
# TODO: three decorated steps, then run them in order and print pd.DataFrame(LOG)
Hint 1

Inside the wrapper: call func(df), then align the two frames on their shared index and columns: before = df.loc[out.index, shared], after = out[shared].

Hint 2

A cell changed when before.ne(after) & ~(before.isna() & after.isna()). Compare a text price with its number as text, or simply accept that a type change counts as a change: "$79.99" != 79.99 is True.

Hint 3

Use functools.wraps(func) so the step keeps its name, and read the name with func.__name__.

Solution
import functools
from collections.abc import Callable
LOG: list[dict] = []
Step = Callable[[pd.DataFrame], pd.DataFrame]
def logged_step(func: Step) -> Step:
@functools.wraps(func)
def wrapper(df: pd.DataFrame) -> pd.DataFrame:
out = func(df)
shared = df.columns.intersection(out.columns)
before, after = df.loc[out.index, shared], out[shared]
both_missing = before.isna() & after.isna()
changed = (before.ne(after) & ~both_missing).to_numpy().sum()
LOG.append(
{
"step": func.__name__,
"rows_in": len(df),
"rows_out": len(out),
"cells_changed": int(changed),
}
)
return out
return wrapper
@logged_step
def drop_exact_duplicates(df: pd.DataFrame) -> pd.DataFrame:
return df.drop_duplicates()
@logged_step
def normalize_region(df: pd.DataFrame) -> pd.DataFrame:
return df.assign(region=df["region"].str.strip().str.title())
@logged_step
def price_to_float(df: pd.DataFrame) -> pd.DataFrame:
digits = df["unit_price"].str.replace(r"[$,]", "", regex=True)
return df.assign(unit_price=pd.to_numeric(digits, errors="coerce"))
raw = pd.read_csv(
"data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"]
)
clean = price_to_float(normalize_region(drop_exact_duplicates(raw)))
print(pd.DataFrame(LOG).to_string(index=False))
assert [r["rows_out"] for r in LOG] == [1164, 1164, 1164]
assert LOG[0]["cells_changed"] == 0
Output
step rows_in rows_out cells_changed
drop_exact_duplicates 1200 1164 0
normalize_region 1164 1164 250
price_to_float 1164 1164 1155

How it works:

  1. The wrapper calls the step, then compares the input and the output cell by cell on the rows and columns they share.
  2. before.ne(after) is True for a changed value and also for a gap that stays a gap. ~both_missing removes those false changes.
  3. Dropping rows changes no cell of the rows that remain, so the duplicate step reports 0 changed cells and 36 fewer rows.
  4. The region step changes fewer cells than in the lesson (250, not 259), because 9 of the bad spellings were in duplicate rows that are already gone.
  5. Every price cell changes because text became a number. The 9 gaps stay gaps, so they do not count.
  6. assign returns a new frame and leaves the input alone, so the wrapper can still compare old and new.

M26-X02 · Find temperature spikes in sensor data

Section titled “M26-X02 · Find temperature spikes in sensor data”
Challenge

data/sensors.csv contains 40 injected temperature spikes of +9 to +18 °C on top of a daily cycle. Compare two detectors per sensor: (a) a z-score above 3 on the temperature of each sensor and (b) the residual from a centered rolling median of 7 readings, flagged when it is above 5 °C. Print the number of flags of each detector, how many they share and the largest residual that was not flagged.

Expected output
z-score flags: 39 | rolling-median flags: 40
shared: 39
largest unflagged residual: 0.71
{'S1': 8, 'S2': 13, 'S3': 11, 'S4': 8}
Starter
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
temp = sensors.groupby("sensor_id")["temperature_c"]
# TODO: detector (a): per-sensor z-score
# TODO: detector (b): residual from a rolling median per sensor
# TODO: print counts, overlap and the largest unflagged residual
Hint 1

temp.transform(lambda s: s.rolling(7, center=True, min_periods=1).median()) gives each reading the median of itself and its 3 neighbors on each side, in the same sensor.

Hint 2

A rolling median ignores a single spike, so the residual temperature - median is near 0 for normal readings and large for a spike. A gap gives a NaN residual, which is never flagged.

Solution
sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
temp = sensors.groupby("sensor_id")["temperature_c"]
z = (sensors["temperature_c"] - temp.transform("mean")) / temp.transform("std")
z_flag = z.abs() > 3
baseline = temp.transform(lambda s: s.rolling(7, center=True, min_periods=1).median())
residual = sensors["temperature_c"] - baseline
spike_flag = residual > 5
print("z-score flags:", z_flag.sum(), "| rolling-median flags:", spike_flag.sum())
print("shared:", (z_flag & spike_flag).sum())
print("largest unflagged residual:", round(residual[~spike_flag].abs().max(), 2))
print(sensors.loc[spike_flag, "sensor_id"].value_counts().sort_index().to_dict())
assert spike_flag.sum() == 40
assert (z_flag & ~spike_flag).sum() == 0
Output
z-score flags: 39 | rolling-median flags: 40
shared: 39
largest unflagged residual: 0.71
{'S1': 8, 'S2': 13, 'S3': 11, 'S4': 8}

How it works:

  1. The z-score compares each reading with the mean of its sensor. The daily cycle and the S3 drift widen the spread, so one spike stays below 3.
  2. The rolling median is a local baseline that follows the daily cycle. One spike cannot move a median of 7 values.
  3. The residuals separate cleanly: normal readings stay within about 0.7 °C of the baseline, and every spike sits far above it. The detector flags 40 readings, the documented number of spikes. The file has no spike label, so this is strong evidence, not proof, that it found the right ones.
  4. Every z-score flag is also a rolling-median flag, so the second detector is strictly better here.

Alternative: a rolling mean would be pulled up by each spike and hide part of it. Use a median for baselines in data with spikes. Note that center=True reads 3 future readings. That is fine for cleaning history; for a live alarm, use a trailing window (center=False), which only looks back.

M26-X03 · Simulate MAR gaps and measure the bias

Section titled “M26-X03 · Simulate MAR gaps and measure the bias”
Challenge

Simulate MAR gaps: hide each known lot_sqft in data/houses.csv with probability 0.4 for houses more than 10 km from the center and 0.05 for the others (np.random.default_rng(42)). Compare the mean lot size of the full data with: the mean of the remaining values (dropping), a global-median fill and a neighborhood-median fill. Also print the MAE of both fills on the hidden values.

Expected output
hidden: 571
true mean 8310
drop rows 7681
global median 7500
neighborhood median 8084
MAE global median 4637
MAE neighborhood median 3037
Starter
houses = pd.read_csv("data/houses.csv")
rng = np.random.default_rng(42)
lot = houses["lot_sqft"]
# TODO: probability per row, random mask, only on known values
# TODO: mar = lot.mask(hide)
# TODO: mean of truth, mean after drop, global-median fill, neighborhood-median fill
# TODO: MAE of the fills on the hidden rows
Hint 1

p = np.where(houses["distance_to_center_km"] > 10, 0.4, 0.05), then hide = (rng.random(len(houses)) < p) & lot.notna().

Hint 2

lot.mask(hide) replaces the values where hide is True with NaN. The truth for the scores is lot[hide].

Solution
houses = pd.read_csv("data/houses.csv")
rng = np.random.default_rng(42)
lot = houses["lot_sqft"]
p = np.where(houses["distance_to_center_km"] > 10, 0.4, 0.05)
hide = (rng.random(len(houses)) < p) & lot.notna()
mar = lot.mask(hide)
global_fill = mar.fillna(mar.median())
area_fill = mar.fillna(mar.groupby(houses["neighborhood"]).transform("median"))
print("hidden:", hide.sum())
print(f"{'true mean':<22}{lot.mean():>8.0f}")
fills = {"global median": global_fill, "neighborhood median": area_fill}
for name, values in {"drop rows": mar, **fills}.items():
print(f"{name:<22}{values.mean():>8.0f}")
for name, values in fills.items():
print(f"MAE {name:<18}{(values[hide] - lot[hide]).abs().mean():>8.0f}")
assert abs(area_fill.mean() - lot.mean()) < abs(mar.mean() - lot.mean())
Output
hidden: 571
true mean 8310
drop rows 7681
global median 7500
neighborhood median 8084
MAE global median 4637
MAE neighborhood median 3037

How it works:

  1. The gaps depend on an observed column, distance, so they are MAR by construction. Far houses have large lots, so far more large lots are hidden.
  2. Dropping rows gives a mean that is too low: the remaining houses are closer to the center than the full set.
  3. A global median is lower still, for two reasons. lot_sqft is right-skewed (median 7,530 below mean 8,310), so a median fill lowers the mean even when gaps are MCAR. And under this MAR mechanism, it gives every far house a typical, smaller lot.
  4. The neighborhood median uses the related information. Neighborhoods differ in distance, so the fill puts large lots back where they belong. The bias almost disappears, and the MAE drops by about a third.

Interpretation: under MAR, a fill that uses the columns which explain the gaps removes most of the bias. Under MNAR, no column explains the gaps, and no fill can remove the bias with certainty.

M26-X04 · A date parser that reports what it did

Section titled “M26-X04 · A date parser that reports what it did”
Challenge

Write parse_dates(s, formats) -> tuple[pd.Series, dict]. It tries each format in order on the values that are still unparsed, and returns the parsed Series and a report: the count per format and the list of raw values that matched no format. Test it on order_date of data/sales_raw.csv with two extra bad values appended.

Expected output
%Y-%m-%d 723
%d/%m/%Y 276
%B %d, %Y 201
unparsed ['2024-13-01', 'soon']
datetime64[us] 1200
Starter
FORMATS = ["%Y-%m-%d", "%d/%m/%Y", "%B %d, %Y"]
def parse_dates(s: pd.Series, formats: list[str]) -> tuple[pd.Series, dict]:
# TODO: start with an all-NaT result
# TODO: for each format, parse only the values that are still NaT
# TODO: report counts per format and the unparsed raw values
...
raw = pd.read_csv("data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"])
dates = pd.concat([raw["order_date"], pd.Series(["2024-13-01", "soon"])], ignore_index=True)
Hint 1

result = pd.Series(pd.NaT, index=s.index, dtype="datetime64[us]") starts with no dates.

Hint 2

In each round, todo = result.isna() & s.notna(). Parse s[todo] with errors="coerce", then write the successes back with result.loc[ok.index] = ok.

Solution
FORMATS = ["%Y-%m-%d", "%d/%m/%Y", "%B %d, %Y"]
def parse_dates(s: pd.Series, formats: list[str]) -> tuple[pd.Series, dict]:
result = pd.Series(pd.NaT, index=s.index, dtype="datetime64[us]")
report: dict = {}
for fmt in formats:
todo = result.isna() & s.notna()
parsed = pd.to_datetime(s[todo], format=fmt, errors="coerce").dropna()
result.loc[parsed.index] = parsed
report[fmt] = len(parsed)
report["unparsed"] = s[result.isna() & s.notna()].tolist()
return result, report
raw = pd.read_csv(
"data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"]
)
extra = pd.Series(["2024-13-01", "soon"])
dates = pd.concat([raw["order_date"], extra], ignore_index=True)
parsed, report = parse_dates(dates, FORMATS)
for name, value in report.items():
print(f"{name:<10} {value}")
print(parsed.dtype, parsed.notna().sum())
assert report["%Y-%m-%d"] == 723 and report["unparsed"] == ["2024-13-01", "soon"]
assert parsed.notna().sum() == 1200
Output
%Y-%m-%d 723
%d/%m/%Y 276
%B %d, %Y 201
unparsed ['2024-13-01', 'soon']
datetime64[us] 1200

How it works:

  1. The result starts as a Series of NaT with the same index as the input.
  2. Each round parses only the values that no earlier format has matched, so a value is never parsed twice, and the counts add up.
  3. dropna() keeps the successes; result.loc[parsed.index] = parsed writes them back by label.
  4. The report shows the format mix and lists the two values that need a person: 2024-13-01 has a month 13, and soon is not a date.

Alternative: in a real pipeline, raise an exception when report["unparsed"] is not empty, or write the unparsed rows to a quarantine file for review.

M26-X05 · Refactor a validation script into a class

Section titled “M26-X05 · Refactor a validation script into a class”
Challenge

Refactor procedural code into OOP: turn the validation rules for the sales table into a Validator class. Each rule is registered with a name and a function that returns a boolean mask of bad rows. run(df) returns a DataFrame with one row per rule: the name and the number of bad rows. Test it on a cleaned copy of data/sales_raw.csv and on the same copy with three errors injected.

Expected output
rule bad_rows
key unique 0
quantity 1..50 10
price present 9
store exists 0
[0, 11, 9, 2] False
Starter
from collections.abc import Callable
Rule = Callable[[pd.DataFrame], pd.Series]
class Validator:
def __init__(self) -> None:
# TODO: store the rules
...
def add(self, name: str, rule: Rule) -> "Validator":
# TODO: register a rule and return self, so calls can be chained
...
def run(self, df: pd.DataFrame) -> pd.DataFrame:
# TODO: one row per rule: name, bad_rows
...
Hint 1

Keep the rules in a list of (name, rule) tuples. run calls each rule and sums its mask.

Hint 2

For the test data, clean only what the rules need: drop duplicates, convert the prices, repair nothing. Then inject errors in a copy with loc.

Hint 3

Add a property ok to the result, or a method passed(df) that returns True when every count is 0.

Solution
from collections.abc import Callable
Rule = Callable[[pd.DataFrame], pd.Series]
class Validator:
"""A named list of rules. Each rule returns True for every bad row."""
def __init__(self) -> None:
self.rules: list[tuple[str, Rule]] = []
def add(self, name: str, rule: Rule) -> "Validator":
self.rules.append((name, rule))
return self
def run(self, df: pd.DataFrame) -> pd.DataFrame:
rows = [{"rule": n, "bad_rows": int(rule(df).sum())} for n, rule in self.rules]
return pd.DataFrame(rows)
def passed(self, df: pd.DataFrame) -> bool:
return bool((self.run(df)["bad_rows"] == 0).all())
stores = pd.read_csv("data/stores.csv")
sales_rules = (
Validator()
.add("key unique", lambda d: d.duplicated(subset=["order_id", "product_id"]))
.add("quantity 1..50", lambda d: ~d["quantity"].between(1, 50))
.add("price present", lambda d: d["unit_price"].isna())
.add("store exists", lambda d: ~d["store_id"].isin(stores["store_id"]))
)
raw = pd.read_csv(
"data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"]
)
sales = raw.drop_duplicates()
sales = sales.assign(
unit_price=pd.to_numeric(sales["unit_price"].str.replace(r"[$,]", "", regex=True))
)
print(sales_rules.run(sales).to_string(index=False))
broken = sales.copy()
broken.loc[broken.index[:2], "store_id"] = "S99"
broken.loc[broken.index[5], "quantity"] = 0
print(sales_rules.run(broken)["bad_rows"].tolist(), sales_rules.passed(broken))
assert sales_rules.run(broken)["bad_rows"].tolist() == [0, 11, 9, 2]
Output
rule bad_rows
key unique 0
quantity 1..50 10
price present 9
store exists 0
[0, 11, 9, 2] False

How it works:

  1. The class holds the rules as data. Adding a rule is one add call; run does not change.
  2. add returns self, so the rules can be chained in one expression.
  3. Each rule is a small lambda that returns a mask of bad rows. run turns the masks into counts.
  4. The first run shows the problems the partial cleaning has not fixed yet: 10 bad quantities and 9 missing prices. The broken copy adds one bad quantity and two orphan stores.
  5. Compared with a function full of if statements, the class separates what the rules are from how they run. Module 22 calls this the strategy pattern.