Lab 2: Clean and Join a Messy Dataset¶
In this lab you clean a messy purchases file, join it with a product table, and use the result to choose a supplier.
The question. Qahwa House buys milk from two suppliers, Hilal Dairy and Tala Farms, and wants to keep only one. Which one, on price and on reliability?
How this lab works
Run the cells from top to bottom with Shift + Enter.
Guided track: replace every
...with your code, then run the check cell under it. A ✅ means your answer is right.Extended track: after Part E, try the ★ challenges at the end.
Submit before the next lab session: File → Download → Download .ipynb, then upload the file to the course page.
You may use an AI assistant for code. If you do, fill in the AI-use log at the end: what you asked, what you kept and what you changed.
# Run this cell once: it defines a small helper that checks your answers.
def check(label, condition):
print(("✅ " if condition else "❌ ") + label)import pandas as pd
BASE = "https://chebil.github.io/BusinessDecision/data/"
def load(name, **kw):
"""Read a course dataset from the website, or from a local copy of the repository."""
try:
return pd.read_csv(BASE + name, **kw)
except Exception:
return pd.read_csv("../data/" + name, **kw)
# "" and "n/a" mean "no value"; everything else is read as it was typed
raw = load("qahwa_purchases_messy.csv", keep_default_na=False, na_values=["", "n/a"])
products = load("qahwa_products.csv")
print(raw.shape, products.shape)Look at the first rows and the type of each column with raw.head() and raw.dtypes. Then find how many different spellings the branch column contains, and store that number in n_spellings. (Qahwa House has four branches.)
n_spellings = ...
print(n_spellings)check("A1 thirteen spellings for four branches", n_spellings == 13)Part B: Clean¶
Work on a copy, so raw stays as it was for the comparison in Part E. We start by removing exact duplicates.
B1. Duplicates¶
Count the exact duplicate rows in raw (store the count in n_dups), then make df a copy of raw without them.
n_dups = ...
df = ...
print(n_dups, len(df))check("B1 duplicates counted", n_dups == 20)
check("B1 duplicates removed", len(df) == len(raw) - 20 and not df.duplicated().any())Which products do the duplicates belong to? Run this and keep the answer in mind for Part E.
raw[raw.duplicated()]["sku"].value_counts()B2. Branch and supplier names¶
Standardise branch: strip spaces, make it lower case, map the variants with the dictionary BRANCH, then use title case. Complete the dictionary. Then standardise supplier the same way (title case, and map “Hilal Dairy Co.” to “Hilal Dairy”).
BRANCH = {"olaya branch": "olaya", ...}
df["branch"] = ...
df["supplier"] = ...
print(df["branch"].value_counts().to_dict())
print(df["supplier"].value_counts().to_dict())check("B2 four branches", sorted(df["branch"].unique()) == ["Al Faisaliyah", "Corniche", "Olaya", "University"])
check("B2 four suppliers", sorted(df["supplier"].unique()) == ["Bunn Roasters", "Hilal Dairy", "Sarawat Roasters", "Tala Farms"])B3. Prices as numbers¶
Remove “SAR” from pack_price, strip spaces, and convert with pd.to_numeric(..., errors="coerce"). The number of missing prices must be the same before and after: anything else means you lost real prices.
missing_before = df["pack_price"].isna().sum()
df["pack_price"] = ...
print(missing_before, df["pack_price"].isna().sum())check("B3 prices are numbers", pd.api.types.is_float_dtype(df["pack_price"]))
check("B3 no price lost", df["pack_price"].isna().sum() == missing_before)B4. Dates¶
Convert date with pd.to_datetime. The file mixes three formats, and staff write the day first (04/03/2025 is the 4th of March). Then check that every date is in 2025. One more fact helps: the suppliers deliver from Sunday to Friday, never on a Saturday.
df["date"] = ...
print(df["date"].min(), df["date"].max())check("B4 dates are dates", pd.api.types.is_datetime64_any_dtype(df["date"]))
check("B4 all in 2025", (df["date"].dt.year == 2025).all())
check("B4 no delivery on a Saturday (day first read correctly)", (df["date"].dt.dayofweek == 5).sum() == 0)B5. Missing values¶
Count the missing values in each column. Then check whether missing prices are spread evenly across suppliers: compute, for each supplier, the share of rows whose price is missing, and store it in missing_share.
print(df.isna().sum())
missing_share = ...
missing_sharecheck("B5 one share per supplier", len(missing_share) == 4 and missing_share.max() < .1)The shares are small and similar, so dropping rows without a price will not bias the cost comparison. We do not drop them yet: their delivery times are still useful for the reliability comparison.
B6. Outliers¶
Apply the IQR rule to Hilal’s pack prices (sku == "HIL-M12"): compute Q1, Q3, the fences, and the flagged prices. Store them, sorted, in flagged.
hil = df.loc[df["sku"] == "HIL-M12", "pack_price"].dropna()
q1, q3 = ...
low, high = ...
flagged = ...
print(round(low, 2), round(high, 2), flagged.tolist())check("B6 five prices flagged", len(flagged) == 5)
check("B6 the two typos are among them", (flagged > 500).sum() == 2)The rule flags five prices, but only two are impossible (a 12-litre carton does not cost 500 SAR). Remove the impossible ones only: drop every row whose pack price is more than three times its product’s median price. Keep the rest, including the 75-carton Ramadan order.
df = ...
print(len(df))check("B6 only the two errors removed", len(df) == len(raw) - 20 - 2)
check("B6 the Ramadan order kept", df["packs"].max() == 75)Part C: Join¶
C1. Add the product information¶
Join df with products on sku to bring in category, unit and units_per_pack. Use a left join, and validate="many_to_one". Store the result in clean. The number of rows must not change.
clean = ...
print(len(df), len(clean))check("C1 same number of rows", len(clean) == len(df))
check("C1 every product found", clean["units_per_pack"].notna().all())C2. Price per unit and late deliveries¶
Add price_per_unit (SAR per litre or per kg) and late (True when delivery_days is above promised_days).
clean["price_per_unit"] = ...
clean["late"] = ...
clean.head()check("C2 Hilal costs about 4.40 SAR a litre", abs(clean.loc[clean["sku"] == "HIL-M12", "price_per_unit"].mean() - 4.40) < .02)Part D: The same question in SQL¶
D1. A supplier summary with DuckDB¶
Run the first cell to load DuckDB. Then write a query on clean that returns, for milk only, each supplier’s average price per litre (sar_per_litre), share of late deliveries (late_share) and number of deliveries, sorted by price. Hint: AVG(CAST(late AS INTEGER)) turns True/False into a share.
# DuckDB runs SQL directly on pandas DataFrames. It is preinstalled in Colab; install it elsewhere if needed.
import importlib.util, subprocess, sys
if importlib.util.find_spec("duckdb") is None:
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "duckdb"], check=True)
import duckdbmilk = duckdb.sql("""
SELECT ...
""").df()
milkcheck("D1 two suppliers", len(milk) == 2)
check("D1 cheapest per litre is Hilal", milk.iloc[0]["supplier"] == "Hilal Dairy")Part E: The decision¶
E1. What the raw file would have said¶
Run this “quick” analysis on the raw file: prices converted as they are, pack prices compared directly, late deliveries counted by product code.
quick = raw.copy()
quick["pack_price"] = pd.to_numeric(quick["pack_price"], errors="coerce")
quick["late"] = quick["delivery_days"] > quick["promised_days"]
quick[quick["sku"].isin(["HIL-M12", "TAL-M10"])].groupby("sku").agg(
pack_price=("pack_price", "mean"), late_share=("late", "mean"), prices_read=("pack_price", "count"), rows=("late", "size")).round(3)E2. What is the switch worth?¶
Qahwa House currently splits its milk between the two suppliers. Estimate how much it would save in a year by buying the litres it now buys from Tala Farms from Hilal Dairy instead, at the average prices you found. Store the result (SAR) in saving.
tala_litres = ...
saving = ...
print(f"{tala_litres:,.0f} litres from Tala, saving {saving:,.0f} SAR a year")check("E2 a positive saving of a few thousand riyals", 3000 < saving < 15000)E3. Your recommendation¶
Write three sentences for the purchasing manager, who does not read code:
what the cleaned data shows, with numbers;
why the raw file pointed the other way;
your recommendation, and one thing you would check before signing.
Write your recommendation here (double-click to edit).
★ Extended challenges¶
X1. Coffee beans. Repeat the comparison for the two coffee-bean suppliers. Is the cheaper one per kilogram also the more reliable one? What would you recommend?
X2. One function. Write clean_purchases(raw, products) that performs every step of Parts B and C and returns clean. Check that it gives the same supplier summary as your step-by-step work.
X3. A wrong dayfirst. Convert the raw dates without dayfirst=True. Does pandas complain? How many deliveries move to a different month, and which of the B4 checks catches the mistake?
# X1# X2# X3AI-use log (if you used an AI assistant)¶
What you asked, what you kept, what you changed.