Part 06 / Topic 2 of 7
Normalising values
Every column gets a normal form, applied mechanically:
# examples/01_clean_the_messy_shipments_export_with.py
import io
import pandas as pd
from fdelab import SHIPMENTS_CSV
df = pd.read_csv(io.StringIO(SHIPMENTS_CSV), dtype=str)
print("raw rows:", len(df))
df["customer"] = df["customer"].str.strip()
df["status"] = df["status"].str.strip().str.lower().str.replace(" ", "_")
# "03/02/2025" is ambiguous (3 Feb or 2 Mar?). Confirm the format with Acme; here month-first is assumed.
df["shipped_on"] = pd.to_datetime(df["shipped_on"], format="mixed", dayfirst=False).dt.date
w = df["weight"].str.extract(r"(?i)^\s*(-?\d+(?:\.\d+)?)\s*(kg|lbs?)\s*$")
df["weight_kg"] = pd.to_numeric(w[0]) * w[1].str.lower().map({"kg": 1.0, "lb": 0.45359237, "lbs": 0.45359237})
df["weight_kg"] = df["weight_kg"].round(2)
df = df.drop_duplicates()
print("after removing exact duplicates:", len(df))
print(df[["shipment_id", "customer", "status", "weight_kg", "shipped_on"]].to_string(index=False))
# raw rows: 8
# after removing exact duplicates: 7
# shipment_id customer status weight_kg shipped_on
# S-1001 Bolt Retail delivered 120.00 2025-03-01
# S-1002 Bolt Retail in_transit 136.08 2025-03-02
# S-1003 Kite Foods delivered 85.00 2025-03-02
# S-1004 Kite Foods delivered NaN 2025-03-04
# S-1005 Nova Pharma delayed 40.00 2025-03-05
# S-1006 Nova Pharma in_transit -5.00 2025-03-06
# S-1007 Bolt Retail delivered 210.00 2025-03-07
Units deserve special respect: 300 lbs is 136.08 kg (ร 0.45359237), and a pipeline that misses the unit ships a 300 kg "fact" into the customer's reports. Extract the number and the unit, convert explicitly, and treat an unknown unit as an error, never a pass-through.
๐งช Quick quiz โ answer from memory, then check.
- How many rows remained after removing exact duplicates from the Acme export?
Show the answer
7 โ 8 raw rows became 7: S-1003 appeared twice. (verified against the example output above)
- What does
300 lbsbecome in kilograms (1 lb = 0.45359237 kg)?
Show the answer
136.08 kg โ 300 ร 0.45359237. (verified against the example output above)
Done here? The practice set for Part 6 โ 4 exercises with solutions โ is on the part page.