Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 2: Clean and Join a Messy Dataset

Open In Colab

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.

Part A: First look

A1. Load and inspect

Run this cell to load the two tables.

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.)

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.

Which products do the duplicates belong to? Run this and keep the answer in mind for Part E.

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”).

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.

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.

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.

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.

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.

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.

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).

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.

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.

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.

E3. Your recommendation

Write three sentences for the purchasing manager, who does not read code:

  1. what the cleaned data shows, with numbers;

  2. why the raw file pointed the other way;

  3. 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?

AI-use log (if you used an AI assistant)

What you asked, what you kept, what you changed.