Data Wrangling: Clean Data Before You Decide¶
Real business data arrives messy: names spelled several ways, numbers stored as text, dates in three formats, rows entered twice, values missing, and the occasional typo that is ten times too large. This reading shows how to find and fix each problem with pandas, how to join two tables, and how to ask the same questions in SQL with DuckDB.
The running example is a real decision. Qahwa House buys milk from two suppliers and wants to keep only one. On the raw file one supplier looks better; on the cleaned file, the other one does. Wrangling is not housekeeping: it decides the decision.
After this reading you can:
check the type of every column and convert text to numbers and dates;
standardise labels, remove duplicates, and choose how to treat missing values;
flag outliers with the IQR rule and tell an error from a real extreme;
join two tables on a key and check the result;
write the same summary in pandas and in SQL.
Textbook: Albright & Winston, Chapter 2 (data types, missing values) and Chapter 18 (importing data).
1. The data: two tables¶
Qahwa House records every delivery of milk and coffee beans in a purchases table, typed in by staff at four branches. A second, small table describes each product the suppliers sell. Both are loaded below.
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)
raw.head(8)productsThe purchases table has one row per delivery: when, where, from whom, which product (sku), how many packs, the price of one pack, and how many days the delivery took against the two days promised. The products table says how much one pack holds: Hilal Dairy sells 12-litre cartons, Tala Farms 10-litre crates.
2. Tidy data and column types¶
A table is tidy when each row is one observation (here, one delivery), each column is one variable, and each cell holds one value. Tidy tables are what pandas, SQL and every chart expect.
The first check is always the type of each column:
raw.dtypespurchase_id object
date object
branch object
supplier object
sku object
packs int64
pack_price object
promised_days int64
delivery_days float64
dtype: objectdate, branch, supplier and pack_price are object: pandas stored them as text. For names that is right. For pack_price it is a problem, because text cannot be averaged. Worse, adding text glues it together instead of failing:
print(raw["pack_price"].head(3).tolist())
print("sum of the first three prices:", raw["pack_price"].head(3).sum())['75.76', 'SAR 367.30', '77.96']
sum of the first three prices: 75.76SAR 367.3077.96
That “sum” is three prices glued into one string. A column that should be numeric but is object is the first sign of messy data.
3. Cleaning labels¶
How many branches does Qahwa House have?
raw["branch"].value_counts()branch
University 101
Corniche 95
Olaya 88
Al Faisaliyah 80
Al-Faisaliyah 44
corniche 38
al faisaliyah 35
Univ. 33
olaya 30
university 28
Corniche (Jeddah) 27
OLAYA 24
Olaya Branch 21
Name: count, dtype: int64Four branches, written thirteen ways: extra spaces, capitals, “Olaya Branch”, “Univ.”. Grouping by this column would split each branch’s deliveries over several groups. The fix has three steps: remove spaces at the ends (strip), use one case (lower), and map the remaining variants to one name.
BRANCH = {"olaya branch": "olaya", "corniche (jeddah)": "corniche", "al-faisaliyah": "al faisaliyah", "univ.": "university"}
df = raw.drop_duplicates().copy() # duplicates are explained in section 5
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}
Always look at value_counts() after cleaning, not only before: a mapping with a typo leaves a fifth “branch” behind.
4. Numbers and dates stored as text¶
Prices were typed as 52.80, SAR 52.80 or 52.80 SAR. Remove the currency, then convert with pd.to_numeric(..., errors="coerce"), which turns anything it cannot read into a missing value (NaN). Then check that the only missing values are the ones that really were empty:
df["pack_price"] = pd.to_numeric(df["pack_price"].str.replace("SAR", "").str.strip(), errors="coerce")
print("missing prices before:", raw.drop_duplicates()["pack_price"].isna().sum(), "| after:", df["pack_price"].isna().sum())missing prices before: 24 | after: 24
The counts agree, so no price was lost in the conversion. Had we skipped the replace, every price written with “SAR” would have become NaN silently.
Dates are trickier. 04/03/2025 is the 4th of March in Saudi Arabia and most of the world, but the 3rd of April in the United States. Our staff write the day first, so we say so:
df["date"] = pd.to_datetime(df["date"], format="mixed", dayfirst=True)
print(df["date"].min().date(), "to", df["date"].max().date())
print(df["date"].dt.month.value_counts().sort_index().to_dict())2025-01-06 to 2025-12-31
{1: 48, 2: 48, 3: 54, 4: 52, 5: 54, 6: 50, 7: 51, 8: 53, 9: 55, 10: 55, 11: 49, 12: 55}
wrong = pd.to_datetime(raw.drop_duplicates()["date"], format="mixed", dayfirst=False)
print("Saturday deliveries, day first:", (df["date"].dt.dayofweek == 5).sum(), "| month first:", (wrong.dt.dayofweek == 5).sum())Saturday deliveries, day first: 0 | month first: 12
Read day-first, no delivery falls on a Saturday; read month-first, twelve do. Checks that come from knowledge of the business are the strongest ones.
Every date falls in 2025 and every month has deliveries. But a wrong dayfirst would pass these checks too: pandas does not fail, it silently reads 04/03 as the 3rd of April. To catch it, test the dates against something you know about the business. Qahwa House’s suppliers deliver from Sunday to Friday, never on a Saturday:
5. Duplicates¶
The same delivery can be typed twice, for example when a complaint form is re-entered. An exact duplicate is a row identical to an earlier one in every column, the purchase number included:
dups = raw[raw.duplicated()]
print(len(dups), "exact duplicates")
dups["sku"].value_counts()20 exact duplicates
sku
HIL-M12 16
BUN-K1 2
SAR-K5 2
Name: count, dtype: int64Most duplicates are Hilal’s milk deliveries, and they are not random ones: they are late deliveries entered a second time. Left in, they make Hilal look less reliable than it is. We removed them at the start of section 3 with drop_duplicates().
6. Missing values¶
Count what is missing in each column:
df.isna().sum()purchase_id 0
date 0
branch 0
supplier 0
sku 0
packs 0
pack_price 24
promised_days 0
delivery_days 18
dtype: int64There are three honest ways to handle a missing value, and the right one depends on the question:
| Strategy | When it fits | Risk |
|---|---|---|
| Drop the row | few values missing, missing for reasons unrelated to the answer | losing data, bias if the missing rows are special |
| Fill it (median, a value from another source) | a sensible value exists | inventing data, hiding uncertainty |
| Flag it (keep a column saying “was missing”) | the fact that it is missing may itself matter | none, but every analysis must decide again |
Before dropping, check whether the missing values are spread evenly. If one supplier’s prices were missing far more often, dropping rows would bias the comparison:
df.groupby("supplier")["pack_price"].apply(lambda s: s.isna().mean()).round(3)supplier
Bunn Roasters 0.038
Hilal Dairy 0.034
Sarawat Roasters 0.029
Tala Farms 0.048
Name: pack_price, dtype: float64Prices are missing at similar, small rates for every supplier, so for the cost comparison we can drop rows without a price. For the delivery comparison we keep those rows, because their delivery time is known. Each question uses all the data that is valid for it.
7. Outliers: error or real extreme?¶
The IQR rule flags values far from the middle half of the data. With and the first and third quartiles and , a value is flagged when it lies below or above .
import matplotlib.pyplot as plt
hil = df.loc[df["sku"] == "HIL-M12", "pack_price"].dropna()
q1, q3 = hil.quantile([.25, .75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
flagged = hil[(hil < low) | (hil > high)]
print(f"Q1 = {q1:.2f}, Q3 = {q3:.2f}, fences {low:.2f} to {high:.2f} SAR")
print("flagged:", flagged.sort_values().tolist())
import numpy as np
fig, ax = plt.subplots(figsize=(7, 2.4))
jitter = np.random.default_rng(1).uniform(-.3, .3, len(hil))
ax.scatter(hil, jitter, s=14, alpha=.6, color=["tab:red" if v in set(flagged) else "tab:blue" for v in hil])
for v in (low, high):
ax.axvline(v, color="grey", ls="--", lw=1)
ax.set_xscale("log")
ax.set_xlabel("Hilal pack price (SAR, log scale); dashed lines: the IQR fences")
ax.set_yticks([])
ax.set_title("Two prices sit ten times above the rest")
plt.show()Q1 = 52.31, Q3 = 53.23, fences 50.93 to 54.61 SAR
flagged: [54.78, 54.96, 55.02, 526.2, 527.4]

The rule flags five prices. It cannot tell you what they are; you must judge each one:
526.2 and 527.4 SAR are impossible for a 12-litre carton that otherwise costs about 53 SAR. They are typing errors (a decimal point lost). We remove them; we could also correct them, if the paper invoice confirmed the true value.
The other three (about 55 SAR) are ordinary price variation, just above a narrow fence. They stay.
Not every extreme is an error. Olaya once ordered 75 cartons, nine times the usual amount:
df.sort_values("packs", ascending=False).head(3)[["purchase_id", "date", "branch", "sku", "packs"]]That order was placed in early March 2025, during Ramadan, when evening traffic jumps. It is real, so it stays: deleting it would make the data less true, not more. Remove errors; keep real extremes, and write down which you did.
df = df[~(df["pack_price"] > 3 * df.groupby("sku")["pack_price"].transform("median"))]
print(len(df), "deliveries after removing duplicates and the two price errors")622 deliveries after removing duplicates and the two price errors
8. Joining tables¶
A Hilal carton costs about 52.80 SAR and a Tala crate about 47.50 SAR, but the packs hold different amounts. The comparison that matters is the price per litre, and the litres per pack live in the products table. We join the two tables on their shared key, sku:
clean = df.merge(products[["sku", "product", "category", "unit", "units_per_pack"]], on="sku",
how="left", validate="many_to_one")
print(len(df), "rows before the join,", len(clean), "after; products not found:", clean["units_per_pack"].isna().sum())
clean["price_per_unit"] = clean["pack_price"] / clean["units_per_pack"]
clean["late"] = clean["delivery_days"] > clean["promised_days"]
clean[["date", "branch", "supplier", "sku", "pack_price", "units_per_pack", "price_per_unit"]].head()622 rows before the join, 622 after; products not found: 0
Two checks follow every join. The number of rows must not change when each delivery matches exactly one product (validate="many_to_one" stops with an error if a key were repeated in products), and no row may fail to find its product. A left join keeps every delivery even when its product is unknown, so failures show up as missing values instead of vanishing.
9. The same question in SQL¶
SQL is the language of databases, and most company data lives in one. DuckDB runs SQL directly on pandas DataFrames, so you can use whichever is clearer for the question:
# 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_sql = duckdb.sql("""
SELECT supplier,
ROUND(AVG(price_per_unit), 3) AS sar_per_litre,
ROUND(AVG(CAST(late AS INTEGER)), 3) AS late_share,
COUNT(*) AS deliveries
FROM clean
WHERE category = 'Milk'
GROUP BY supplier
ORDER BY sar_per_litre
""").df()
milk_sqlAVG ignores missing prices, just as pandas does. The same summary in pandas:
clean[clean["category"] == "Milk"].groupby("supplier").agg(
sar_per_litre=("price_per_unit", "mean"), late_share=("late", "mean"), deliveries=("late", "size")).round(3)10. What the cleaning changed¶
Here is the “quick” analysis someone might do on the raw file: convert the price column as it is, and compare pack prices and late deliveries 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)The quick analysis says Tala Farms is cheaper and more reliable. It is wrong on both counts:
it compares packs of different sizes, half the prices were not read at all (every one written with “SAR”), and two typos inflate Hilal’s average;
Hilal’s late deliveries are counted twice.
Cleaned and joined, Hilal Dairy costs about 4.40 SAR a litre against 4.76 for Tala, and is late 7.8% of the time against 9.6%. The same data, wrangled honestly, reverses the decision.
Check your understanding¶
A column of prices has type
object. Name two things that could cause this.Why is
errors="coerce"dangerous if you do not count missing values before and after?What does
04/03/2025mean in a file typed in Riyadh, and how do you tell pandas?When is dropping rows with a missing value a bad idea?
The IQR rule flags a delivery of 75 cartons. Should you remove it?
A join turned 412 rows into 430. What happened?
Answers. 1. Text mixed into the numbers (“SAR 52.80”, “n/a”), or a decimal comma. 2. It turns unreadable values into NaN without telling you, so real prices can disappear. 3. The 4th of March; pd.to_datetime(..., dayfirst=True). 4. When the missing rows differ from the others, for example if one supplier’s prices are missing much more often. 5. Not without checking: here it was a real Ramadan order, so it stays. 6. A key was repeated in the right-hand table, so some rows matched twice; validate="many_to_one" catches this.