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 Solutions: Clean and Join a Messy Dataset

Open In Colab

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.

Part A: First look

A1. Load and inspect

Run this cell to load the two tables.

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

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
Loading...
✅ 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.

20 624
✅ B1 duplicates counted
✅ B1 duplicates removed

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

sku HIL-M12 16 BUN-K1 2 SAR-K5 2 Name: count, dtype: int64

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

{'Al Faisaliyah': 156, 'Corniche': 156, 'Olaya': 156, 'University': 156}
{'Tala Farms': 208, 'Hilal Dairy': 208, 'Sarawat Roasters': 104, 'Bunn Roasters': 104}
✅ 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.

24
 24
✅ 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.

2025-01-06 00:00:00 2025-12-31 00:00:00
✅ 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.

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: float64
✅ 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.

50.93 54.61 [54.78, 54.96, 55.02, 526.2, 527.4]
✅ 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.

622
✅ 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.

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

Loading...
✅ 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.

Loading...
✅ 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.

Loading...

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.

22,000 litres from Tala, saving 7,814 SAR a year
✅ E2 a positive saving of a few thousand riyals

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.

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?

Loading...

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.

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