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:
- Read the task and the expected output.
- Copy the setup block and the starter code into a script and replace each to-do comment with your code.
- Run the script. Compare your output with the expected output.
- 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 npimport pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)Warm-up
Section titled “Warm-up”M26-W01 · Find the columns with gaps
Section titled “M26-W01 · Find the columns with gaps”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.
data/customers.csv total_charges 10 (0.2%)data/houses.csv lot_sqft 90 (3.0%)data/houses.csv school_rating 90 (3.0%)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, percentHint 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] = countassert found == {"total_charges": 10, "lot_sqft": 90, "school_rating": 90}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:
isna()marks every missing cell.sum()counts theTruevalues per column.counts[counts > 0]keeps only the columns with gaps..items()gives (name, count) pairs.- 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”Predict the output: what does each line print? Write your answers before you run the code.
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 codeAcceptance 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.0assert len(s) - s.count() == 1False16.0 3.02 3nanHow it works:
s == np.nanisFalseeverywhere, even at the gap, so.any()isFalse. This is why you must useisna().isna().sum()counts the one gap.sum()adds 2 and 4.mean()divides by the 2 present values, not by 3.count()is 2 andlen()is 3. Their difference is the number of gaps.- With
skipna=False, one gap makes the whole resultNaN.
M26-W03 · Declare the missing-value tokens
Section titled “M26-W03 · Declare the missing-value tokens”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.
default str gaps: 17strict float64 gaps: 24default = 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 loadsHint 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() == 24assert strict["discount"].dtype == "float64"default str gaps: 17strict float64 gaps: 24How it works:
- With the defaults, the 7 dashes stay as text. One text value makes the whole column
str, and only 17 cells count as gaps. - With explicit tokens, all 24 gaps are
NaNand the rest are numbers, so pandas loads the column asfloat64. 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”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.
float64 10 1299.0raw = 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 maxHint 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() == 10assert price.max() == 1299.0float64 10 1299.0How it works:
- The character class
[$,]matches one character that is either$or,. Inside a class,$is a plain character. - One
replacecall removes both kinds of junk. - 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).
M26-W05 · Normalize a channel column
Section titled “M26-W05 · Normalize a channel column”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.
{'online': 4, 'store': 2, nan: 1}channel = pd.Series([" Online", "STORE", "store ", "online", None, "web", "Web "])# TODO: strip, lower case, map "web" to "online"# TODO: print value_counts with the gapsHint 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"] == 2assert clean.isna().sum() == 1{'online': 4, 'store': 2, nan: 1}How it works:
.str.strip()removes the spaces at both ends..str.lower()makes the case equal.replacewith a dict rewrites whole values. It runs after the normalization, so"Web "has already become"web".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”Predict the output: an order system wrote one order line twice and corrected the discount of another line. What does each line print?
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 codeAcceptance 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() == 1assert lines.duplicated(subset=key).sum() == 2[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:
- Exact test: only row 1 equals an earlier row in every column. The
O2rows differ indiscount. - Key test: rows 1 and 3 repeat an earlier key.
keep="last"marks the earlier copies instead: rows 0 and 2.keep=Falsemarks all 4 rows that belong to a duplicate group.- Keeping the last copy keeps the corrected discount 0.1 for
O2.
M26-W07 · Parse one date format strictly
Section titled “M26-W07 · Parse one date format strictly”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.
['2023-01-07', '2023-01-13', nan, nan, '2024-12-01']could not parse: 2['31/02/2024', '2024-03-05']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 failedHint 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() == 2assert parsed.iloc[0] == pd.Timestamp("2023-01-07")['2023-01-07', '2023-01-13', nan, nan, '2024-12-01']could not parse: 2['31/02/2024', '2024-03-05']How it works:
- The explicit format reads the day first, so
07/01/2023becomes 7 January. 31/02/2024fits the pattern but is not a real date (February has no 31st).2024-03-05has another format. Both becomeNaT.strftimeturnsNaTintoNaN, whichtolist()shows asnan.- Listing the failures tells you what to do next: the ISO value needs a second format; the impossible date needs a human.
M26-W08 · Compute IQR fences
Section titled “M26-W08 · Compute IQR fences”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.
Q1 1350 | Q3 2210 | IQR 860fences 60 to 3500 | outside: 88sqft = pd.read_csv("data/houses.csv")["sqft"]# TODO: Q1, Q3 and IQR# TODO: lower and upper fence, number of houses outsideHint 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 - q1lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqroutside = ~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() < upperQ1 1350 | Q3 2210 | IQR 860fences 60 to 3500 | outside: 88How it works:
- The quartiles cut the sorted values into quarters. The IQR is the width of the middle half.
- The fences lie 1.5 IQR below Q1 and above Q3.
betweenincludes both ends, so~betweenis exactly “below the lower or above the upper fence”.- 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”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.
median: 6.0flagged: 90gaps left: 0houses = pd.read_csv("data/houses.csv")# TODO: add the indicator column first# TODO: fill with the median, print median, flagged rows and gaps leftHint 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() == 90assert houses["school_rating"].isna().sum() == 0median: 6.0flagged: 90gaps left: 0How it works:
- The indicator is a copy of the gap mask, saved as a column. It must come first.
median()skips the gaps, so it is the median of the 2,910 known ratings.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.
M26-C01 · Map the missingness pattern
Section titled “M26-C01 · Map the missingness pattern”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.
lot_sqft school_ratingFalse False 2821 True 89True False 89 True 1Name: count, dtype: int64complete rows: 94.0%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 rowsHint 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)] == 1lot_sqft school_ratingFalse False 2821 True 89True False 89 True 1Name: count, dtype: int64complete rows: 94.0%How it works:
isna()turns each row into a pattern such as (False,True): rating missing, lot known.value_counts()on the two-column table counts each pattern. The index is a pair of booleans.- 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. notna().all(axis=1)isTruefor 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?”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?
sqft distance_to_center_km pricelot_missingFalse 1856.4 8.6 475960.8True 1863.4 8.1 492783.3{'sqft': 0.921, 'distance_to_center_km': 0.432, 'price': 0.61}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 commentHint 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 sqft distance_to_center_km pricelot_missingFalse 1856.4 8.6 475960.8True 1863.4 8.1 492783.3{'sqft': 0.921, 'distance_to_center_km': 0.432, 'price': 0.61}How it works:
- The
groupbykey is the gap mask, renamed tolot_missingso the table is readable. - The permutation loop moves the 90 gaps to random houses 1,000 times. Each shuffle gives a difference that chance alone produces.
- 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”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.
neighborhoodCedar Park 10Downtown 11Lakeview 6Maple Grove 17Oak Hill 12Old Town 10Riverside 10Westfield 14Name: count, dtype: int64Int64 1 10 0houses = 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/maxHint 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()neighborhoodCedar Park 10Downtown 11Lakeview 6Maple Grove 17Oak Hill 12Old Town 10Riverside 10Westfield 14Name: count, dtype: int64Int64 1 10 0How it works:
transform("median")computes the median per neighborhood and broadcasts it back to every row of that neighborhood.fillnauses that per-row value only where the rating is missing.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.Int64stores whole numbers and would keep any remaining gap aspd.NA.float64would 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”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.
tenure: [0] | signup months: ['2024-12']rule holds for 99.98% of customerscustomers = 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 * tenureHint 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() == 0tenure: [0] | signup months: ['2024-12']rule holds for 99.98% of customersHow it works:
- 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.
fillna(0.0)applies the rule. The mean, about 1,386 USD, would invent charges for customers who never paid.np.isclosewithrtol=0.06checks the documented relationship.atol=0.01handles the expected value 0, where a relative tolerance alone would demand exact equality.- 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.
M26-C05 · Keep the latest correction
Section titled “M26-C05 · Keep the latest correction”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.
5 -> 3 order_id product_id quantity discount updated_at1 O000051 P001 1 0.05 2023-01-04 09:00:003 O000051 P029 4 0.00 2023-01-04 17:30:004 O000062 P028 2 0.00 2023-01-06 08:15:00edits = 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 lastHint 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() == 25 -> 3 order_id product_id quantity discount updated_at1 O000051 P001 1 0.05 2023-01-04 09:00:003 O000051 P029 4 0.00 2023-01-04 17:30:004 O000062 P028 2 0.00 2023-01-06 08:15:00How it works:
sort_values("updated_at")puts every edit in time order.drop_duplicates(subset=key, keep="last")keeps the newest row per key. TheP029line keeps its corrected discount 0.0 instead of the gap.- The final
sort_values(key)only makes the output easy to read. - 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.
M26-C06 · Find near-duplicate names
Section titled “M26-C06 · Find near-duplicate names”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.
duplicates: 0 -> 2line 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")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 numberHint 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() == 2duplicates: 0 -> 2line 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:
normalize("NFC")turns the decomposede+ accent into oneé, so equal-looking names become equal strings.strip, the\s+replacement andtitleremove the spacing and case differences.- After normalization, lines 1 and 8 and lines 2 and 13 are the same person. Before it,
==saw no duplicate at all. title()capitalizes after the apostrophe, soo'brienbecomesO'Brien. It is a reasonable rule here, but it would turnMcDonaldintoMcdonald: 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”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.
quick parse: False | explicit parse: Truedates that change: 269 | NaT: 0raw = 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 againHint 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 = Nonefor 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() == 0quick parse: False | explicit parse: Truedates that change: 269 | NaT: 0How it works:
rises_with_idtakes the earliest date of each order and checks that the sequence never goes down when the order ids are sorted.- The quick parse fails the check: with
dayfirst=True, pandas reads ISO dates such as2023-01-04as 1 April. - The loop parses each format strictly and fills the gaps of the result from the next format.
- 269 dates change, and the check passes. A parse with no
NaTis 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”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.
gaps: 10 | mean: 139.65raw = 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 loopHint 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() == 10assert fast.dtype == "float64"gaps: 10 | mean: 139.65How it works:
- The vectorized version runs each string operation once over the whole column. The gaps pass through
.strmethods untouched. pd.to_numeric(..., errors="coerce")replaces thefloat()call and theisnabranch at once.assert_series_equalcompares values, dtype, index and name, so the refactor is proven equal.- There is one difference in behavior: on a value such as
"n/a", the loop raises aValueErrorand the vectorized version givesNaN. 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”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.
ffill MAE 0.601interpolate MAE 0.391gaps left: 0sensors = 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 methodHint 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.nanby_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() == 0ffill MAE 0.601interpolate MAE 0.391gaps left: 0How it works:
- The hidden values have a known truth, so the error of each method can be measured.
- Both fills run per sensor, so a gap never borrows a value from another sensor.
- 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.
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”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.
IQR on price flagged 198 | injected 2z on price flagged 68 | injected 1IQR on log price flagged 44 | injected 1robust z on log flagged 7 | injected 1houses = 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 countsHint 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()IQR on price flagged 198 | injected 2z on price flagged 68 | injected 1IQR on log price flagged 44 | injected 1robust z on log flagged 7 | injected 1How it works:
- Each function returns a boolean mask, so the rules are easy to compare and combine.
- On the raw price, both rules flag the expensive tail, and the z-score flags fewer because the tail inflates the standard deviation.
- The log compresses the tail, so the rules on the log price flag far fewer houses.
- 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”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.
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']}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 rowsHint 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"]}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:
- A left merge keeps every line of
extra.indicator=Trueadds_mergewithbothorleft_only. S13andP031do not exist, so their lines are orphans.s02is an orphan too: the store exists asS02, but keys are case-sensitive. A normalization step (.str.upper()) would fix that line; the other two need the partner to correct their data.value_counts()also listsright_onlywith 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”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.
['lot_sqft: 90 missing', 'school_rating: 90 missing'][]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 copyHint 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)) == 2assert validate_houses(filled) == []['lot_sqft: 90 missing', 'school_rating: 90 missing'][]How it works:
- Each rule is one
ifthat appends a message. The function never stops early, so you see all problems at once. - The range check on
school_ratingusesdropna(), so a gap is reported once, by the missing-value rule, and not twice. bathrooms * 2 % 1 == 0isTruefor 1.0, 1.5, 2.0 and so on. The values are exact halves in binary, so the float test is safe here.- 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”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.
observed only r = 0.730global mean fill r = 0.719neighborhood median fill r = 0.734houses = 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"]observed only r = 0.730global mean fill r = 0.719neighborhood median fill r = 0.734How it works:
- The observed correlation uses the 2,910 houses with a value.
- 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.
- 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.
Challenge
Section titled “Challenge”M26-X01 · A decorator that logs each cleaning step
Section titled “M26-X01 · A decorator that logs each cleaning step”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.
step rows_in rows_out cells_changeddrop_exact_duplicates 1200 1164 0 normalize_region 1164 1164 250 price_to_float 1164 1164 1155import functoolsfrom 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 functoolsfrom 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_stepdef drop_exact_duplicates(df: pd.DataFrame) -> pd.DataFrame: return df.drop_duplicates()
@logged_stepdef normalize_region(df: pd.DataFrame) -> pd.DataFrame: return df.assign(region=df["region"].str.strip().str.title())
@logged_stepdef 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 step rows_in rows_out cells_changeddrop_exact_duplicates 1200 1164 0 normalize_region 1164 1164 250 price_to_float 1164 1164 1155How it works:
- The wrapper calls the step, then compares the input and the output cell by cell on the rows and columns they share.
before.ne(after)isTruefor a changed value and also for a gap that stays a gap.~both_missingremoves those false changes.- Dropping rows changes no cell of the rows that remain, so the duplicate step reports 0 changed cells and 36 fewer rows.
- 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.
- Every price cell changes because text became a number. The 9 gaps stay gaps, so they do not count.
assignreturns 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”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.
z-score flags: 39 | rolling-median flags: 40shared: 39largest unflagged residual: 0.71{'S1': 8, 'S2': 13, 'S3': 11, 'S4': 8}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 residualHint 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() > 3baseline = temp.transform(lambda s: s.rolling(7, center=True, min_periods=1).median())residual = sensors["temperature_c"] - baselinespike_flag = residual > 5print("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() == 40assert (z_flag & ~spike_flag).sum() == 0z-score flags: 39 | rolling-median flags: 40shared: 39largest unflagged residual: 0.71{'S1': 8, 'S2': 13, 'S3': 11, 'S4': 8}How it works:
- 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.
- The rolling median is a local baseline that follows the daily cycle. One spike cannot move a median of 7 values.
- 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.
- 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”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.
hidden: 571true mean 8310drop rows 7681global median 7500neighborhood median 8084MAE global median 4637MAE neighborhood median 3037houses = 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 rowsHint 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())hidden: 571true mean 8310drop rows 7681global median 7500neighborhood median 8084MAE global median 4637MAE neighborhood median 3037How it works:
- 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.
- Dropping rows gives a mean that is too low: the remaining houses are closer to the center than the full set.
- A global median is lower still, for two reasons.
lot_sqftis 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. - 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”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.
%Y-%m-%d 723%d/%m/%Y 276%B %d, %Y 201unparsed ['2024-13-01', 'soon']datetime64[us] 1200FORMATS = ["%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%Y-%m-%d 723%d/%m/%Y 276%B %d, %Y 201unparsed ['2024-13-01', 'soon']datetime64[us] 1200How it works:
- The result starts as a Series of
NaTwith the same index as the input. - Each round parses only the values that no earlier format has matched, so a value is never parsed twice, and the counts add up.
dropna()keeps the successes;result.loc[parsed.index] = parsedwrites them back by label.- The report shows the format mix and lists the two values that need a person:
2024-13-01has a month 13, andsoonis 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”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.
rule bad_rows key unique 0quantity 1..50 10 price present 9 store exists 0[0, 11, 9, 2] Falsefrom 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"] = 0print(sales_rules.run(broken)["bad_rows"].tolist(), sales_rules.passed(broken))assert sales_rules.run(broken)["bad_rows"].tolist() == [0, 11, 9, 2] rule bad_rows key unique 0quantity 1..50 10 price present 9 store exists 0[0, 11, 9, 2] FalseHow it works:
- The class holds the rules as data. Adding a rule is one
addcall;rundoes not change. addreturnsself, so the rules can be chained in one expression.- Each rule is a small
lambdathat returns a mask of bad rows.runturns the masks into counts. - 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.
- Compared with a function full of
ifstatements, the class separates what the rules are from how they run. Module 22 calls this the strategy pattern.