Lab 2 Solutions: Clean and Join a Messy Dataset¶
These are the worked solutions, with outputs. Try the lab yourself first.
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)(644, 9) (4, 6)
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.)
print(raw.dtypes)
n_spellings = raw["branch"].nunique()
print(n_spellings)
raw.head()purchase_id object
date object
branch object
supplier object
sku object
packs int64
pack_price object
promised_days int64
delivery_days float64
dtype: object
13
check("A1 thirteen spellings for four branches", n_spellings == 13)✅ A1 thirteen spellings for four branches
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 = raw.duplicated().sum()
df = raw.drop_duplicates().copy()
print(n_dups, len(df))20 624
check("B1 duplicates counted", n_dups == 20)
check("B1 duplicates removed", len(df) == len(raw) - 20 and not df.duplicated().any())✅ B1 duplicates counted
✅ B1 duplicates removed
Which products do the duplicates belong to? Run this and keep the answer in mind for Part E.
raw[raw.duplicated()]["sku"].value_counts()sku
HIL-M12 16
BUN-K1 2
SAR-K5 2
Name: count, dtype: int64B2. 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", "corniche (jeddah)": "corniche", "al-faisaliyah": "al faisaliyah", "univ.": "university"}
df["branch"] = df["branch"].str.strip().str.lower().replace(BRANCH).str.title()
df["supplier"] = df["supplier"].str.strip().str.title().replace({"Hilal Dairy Co.": "Hilal Dairy"})
print(df["branch"].value_counts().to_dict())
print(df["supplier"].value_counts().to_dict()){'Al Faisaliyah': 156, 'Corniche': 156, 'Olaya': 156, 'University': 156}
{'Tala Farms': 208, 'Hilal Dairy': 208, 'Sarawat Roasters': 104, 'Bunn Roasters': 104}
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"])✅ B2 four branches
✅ B2 four suppliers
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"] = pd.to_numeric(df["pack_price"].str.replace("SAR", "").str.strip(), errors="coerce")
print(missing_before, df["pack_price"].isna().sum())24 24
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)✅ B3 prices are numbers
✅ B3 no price lost
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"] = pd.to_datetime(df["date"], format="mixed", dayfirst=True)
print(df["date"].min(), df["date"].max())2025-01-06 00:00:00 2025-12-31 00:00:00
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)✅ B4 dates are dates
✅ B4 all in 2025
✅ B4 no delivery on a Saturday (day first read correctly)
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 = df.groupby("supplier")["pack_price"].apply(lambda s: s.isna().mean())
missing_share.round(3)purchase_id 0
date 0
branch 0
supplier 0
sku 0
packs 0
pack_price 24
promised_days 0
delivery_days 18
dtype: int64
supplier
Bunn Roasters 0.038
Hilal Dairy 0.034
Sarawat Roasters 0.029
Tala Farms 0.048
Name: pack_price, dtype: float64check("B5 one share per supplier", len(missing_share) == 4 and missing_share.max() < .1)✅ B5 one share per supplier
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 = hil.quantile([.25, .75])
low, high = q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1)
flagged = hil[(hil < low) | (hil > high)].sort_values()
print(round(low, 2), round(high, 2), flagged.tolist())50.93 54.61 [54.78, 54.96, 55.02, 526.2, 527.4]
check("B6 five prices flagged", len(flagged) == 5)
check("B6 the two typos are among them", (flagged > 500).sum() == 2)✅ B6 five prices flagged
✅ B6 the two typos are among them
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 = df[~(df["pack_price"] > 3 * df.groupby("sku")["pack_price"].transform("median"))]
print(len(df))622
check("B6 only the two errors removed", len(df) == len(raw) - 20 - 2)
check("B6 the Ramadan order kept", df["packs"].max() == 75)✅ B6 only the two errors removed
✅ B6 the Ramadan order kept
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 = df.merge(products[["sku", "category", "unit", "units_per_pack"]], on="sku", how="left", validate="many_to_one")
print(len(df), len(clean))622 622
check("C1 same number of rows", len(clean) == len(df))
check("C1 every product found", clean["units_per_pack"].notna().all())✅ C1 same number of rows
✅ C1 every product found
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["pack_price"] / clean["units_per_pack"]
clean["late"] = clean["delivery_days"] > clean["promised_days"]
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)✅ C2 Hilal costs about 4.40 SAR a litre
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 supplier,
AVG(price_per_unit) AS sar_per_litre,
AVG(CAST(late AS INTEGER)) AS late_share,
COUNT(*) AS deliveries
FROM clean
WHERE category = 'Milk'
GROUP BY supplier
ORDER BY sar_per_litre
""").df()
milk.round(3)check("D1 two suppliers", len(milk) == 2)
check("D1 cheapest per litre is Hilal", milk.iloc[0]["supplier"] == "Hilal Dairy")✅ D1 two suppliers
✅ D1 cheapest per litre is Hilal
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.
milk_rows = clean[clean["category"] == "Milk"]
tala_litres = (milk_rows.loc[milk_rows["supplier"] == "Tala Farms", "packs"] * 10).sum()
per_litre = milk_rows.groupby("supplier")["price_per_unit"].mean()
saving = tala_litres * (per_litre["Tala Farms"] - per_litre["Hilal Dairy"])
print(f"{tala_litres:,.0f} litres from Tala, saving {saving:,.0f} SAR a year")22,000 litres from Tala, saving 7,814 SAR a year
check("E2 a positive saving of a few thousand riyals", 3000 < saving < 15000)✅ E2 a positive saving of a few thousand riyals
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.
Recommendation. After cleaning, Hilal Dairy’s milk costs 4.40 SAR a litre against 4.76 SAR for Tala Farms, and Hilal delivers late 7.8% of the time against 9.6%. The raw file pointed the other way because it compared a 12-litre carton with a 10-litre crate, failed to read every price written with “SAR”, kept two prices typed ten times too large, and counted Hilal’s late deliveries twice. I recommend moving all milk purchases to Hilal Dairy, which would save about 7,800 SAR a year at 2025 volumes; before signing, I would confirm that Hilal can supply the extra volume, especially during Ramadan.
★ 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: coffee beans
clean[clean["category"] == "Coffee beans"].groupby("supplier").agg(
sar_per_kg=("price_per_unit", "mean"), late_share=("late", "mean"), deliveries=("late", "size")).round(3)Sarawat Roasters is cheaper per kilogram (about 73 SAR against 78 SAR for Bunn Roasters, thanks to its 5 kg sacks) but late twice as often. The choice depends on what a late delivery costs a café: if a branch runs out of beans, the 5 SAR a kilo saved is quickly lost. A sensible plan keeps Sarawat for planned stock and Bunn as a reliable backup.
# X2: the whole cleaning as one function
def clean_purchases(raw, products):
df = raw.drop_duplicates().copy()
df["branch"] = df["branch"].str.strip().str.lower().replace(BRANCH).str.title()
df["supplier"] = df["supplier"].str.strip().str.title().replace({"Hilal Dairy Co.": "Hilal Dairy"})
df["pack_price"] = pd.to_numeric(df["pack_price"].str.replace("SAR", "").str.strip(), errors="coerce")
df["date"] = pd.to_datetime(df["date"], format="mixed", dayfirst=True)
df = df[~(df["pack_price"] > 3 * df.groupby("sku")["pack_price"].transform("median"))]
out = df.merge(products[["sku", "category", "unit", "units_per_pack"]], on="sku", how="left", validate="many_to_one")
out["price_per_unit"] = out["pack_price"] / out["units_per_pack"]
out["late"] = out["delivery_days"] > out["promised_days"]
return out
again = clean_purchases(raw, products)
print(again.shape == clean.shape, again["price_per_unit"].mean().round(4) == clean["price_per_unit"].mean().round(4))True True
# X3: the cost of a wrong dayfirst
wrong = pd.to_datetime(raw["date"], format="mixed", dayfirst=False, errors="coerce")
right = pd.to_datetime(raw["date"], format="mixed", dayfirst=True)
print("unreadable with the wrong convention:", wrong.isna().sum())
print("read, but in another month:", ((wrong.dt.month != right.dt.month) & wrong.notna()).sum())
print("Saturday deliveries:", (wrong.dt.dayofweek == 5).sum())unreadable with the wrong convention: 0
read, but in another month: 68
Saturday deliveries: 12
pandas does not complain: read month-first, 04/03/2025 silently becomes the 3rd of April, and a date it cannot read that way, such as 25/03/2025, is quietly read day-first instead. Sixty-eight deliveries land in the wrong month, yet every date is still in 2025 and every month still has deliveries. Only the Saturday check catches it, because it tests the dates against a fact about the business.