Module 3 of 6 · 50 minutes

Cleaning data

Cleaning is a series of judgement calls. This module shows how to make them well — and how to leave a trail others can follow.

By · Last updated

Learning objectives

  • Clean on a copy and log every decision
  • Remove duplicates and standardise categories
  • Fix types and invalid values
  • Choose a missing-value strategy
  • Investigate and handle outliers
  • Verify cleaning by comparing before and after
  • Tidy text without removing meaning, and use AI assistants for cleaning safely
Setup: the practice data from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport pandas as pd
import numpy as np

customers = pd.DataFrame({
    "customer_id": [101, 102, 103, 103, 104, 105, 106, 107, 108, 109],
    "signup_date": ["2025-01-04", "04/02/2025", "2025-02-10", "2025-02-10", "2025-03-15",
                    "2025-13-01", "2025-04-02", None, "2025-05-20", "2025-06-01"],
    "country": ["UK", "United Kingdom", "uk", "uk", "Ireland", "UK", "IE", "UK", "U.K.", "UK"],
    "age": [34, 29, None, None, 41, 230, 38, 27, -1, 52],
    "monthly_spend": [42.5, 18.0, 63.2, 63.2, None, 25.0, 12000.0, 31.4, 22.0, 47.9],
    "churned": ["no", "yes", "No", "No", "no", "yes", "no", "YES", "no", "no"],
})

3.1 Work on a copy and log every decision

clean = customers.copy()
decisions = {}      # a log: what was done, why, and to how many rows

def log(step, reason, rows):
    if step in decisions and rows == 0:
        return                      # re-running a cell on already-clean data: keep the first entry
    decisions[step] = {"reason": reason, "rows_affected": int(rows)}

Never overwrite the raw data. Keeping customers untouched means you can always compare before and after, and start again if a decision turns out to be wrong. (To start this page again from scratch, press Run on the cell above.)

3.2 Duplicates

n = clean.duplicated().sum()
clean = clean.drop_duplicates().reset_index(drop=True)
log("drop exact duplicates", "customer 103 appeared twice", n)
print(len(customers), "rows before,", len(clean), "after")

Watch for near-duplicates too — the same person with a slightly different email or name spelling — which need matching rules or record-linkage tools.

3.3 Standardise categories

country_map = {"uk": "UK", "united kingdom": "UK", "u.k.": "UK",
               "ireland": "IE", "ie": "IE"}
before = clean["country"].copy()
clean["country"] = clean["country"].str.strip().str.lower().map(country_map).fillna(clean["country"])
log("standardise country", "five spellings of UK, two of Ireland", (before != clean["country"]).sum())

clean["churned"] = (clean["churned"].astype(str).str.strip().str.lower()
                    .map({"yes": True, "no": False, "true": True, "false": False}))
print(clean[["country", "churned"]].value_counts())

The .fillna(clean["country"]) at the end is deliberate: a spelling that isn't in the map is left as it was, not silently turned into a missing value. Unknown values should stay visible so that someone decides what they mean.

3.4 Fix types and invalid values

as_text = clean["signup_date"].astype(str)
dates = pd.to_datetime(as_text, format="%Y-%m-%d", errors="coerce")
alt   = pd.to_datetime(as_text, format="%d/%m/%Y", errors="coerce")   # UK day/month format
clean["signup_date"] = dates.fillna(alt)          # "2025-13-01" stays missing: invalid

invalid_age = (clean["age"] < 16) | (clean["age"] > 110)
log("set impossible ages to missing", "230 and -1 are not valid ages", invalid_age.sum())
clean.loc[invalid_age, "age"] = np.nan
print(clean[["customer_id", "signup_date", "age"]])

Note: "04/02/2025" could mean 4 February (UK) or 2 April (US). Ambiguous formats must be resolved by knowing the source system — don't guess.

3.5 Missing values: choose a strategy

StrategyWhen it fitsRisk
Drop rowsFew rows affected, missing at randomLoses data; can bias the sample if missingness isn't random
Drop columnMostly empty and not essentialLoses a possibly useful signal
Fill with median / modeSmall gaps in numeric or categorical dataShrinks variation; hides uncertainty
Fill with a model (imputation)Values predictable from other columnsMore complex; can leak information if done before splitting
Keep and flagMissingness itself may be meaningfulModels must handle the flag
if "age_missing" not in clean:                             # only the first time this cell runs
    clean["age_missing"] = clean["age"].isna()             # keep the signal
median_age = clean["age"].median()
clean["age"] = clean["age"].fillna(median_age)
log("fill missing age with median", f"median = {median_age}", clean["age_missing"].sum())
print(clean[["customer_id", "age", "age_missing"]])
Fit cleaning on training data only

Statistics used to fill values (medians, means, scalers) should be calculated from the training data and then applied to test data. Calculating them on all data leaks information from the test set (Module 5).

Why ask whether values are "missing at random"? Suppose older customers are less likely to give their age. Dropping rows with no age would then remove older customers, and filling with the median would make them look younger than they are. Before choosing a strategy, check whether the rows with gaps differ from the rest — for example, compare their churn rate or spend.

3.6 Outliers: investigate, then decide

suspect = clean["monthly_spend"] > 1000
print(clean[suspect])
# After checking with the finance team: 12000.0 was entered in pence, not pounds.
clean.loc[suspect, "monthly_spend"] = clean.loc[suspect, "monthly_spend"] / 100
log("convert spend entered in pence", "confirmed with finance team", suspect.sum())

print(pd.DataFrame(decisions).T)

Other options include capping (winsorising) extreme values, transforming skewed data (e.g. log), or keeping genuine extremes and using models that are robust to them.

3.7 Prove the cleaning worked

Cleaning isn't finished until you've measured the result against the profile you took at the start. Ask the same questions of both tables:

Python · before and afterdef summary(df):
    return pd.Series({
        "rows": len(df),
        "repeated IDs": int(df["customer_id"].duplicated().sum()),
        "country values": df["country"].nunique(),
        "missing ages": int(df["age"].isna().sum()),
        "impossible ages": int((~df["age"].between(16, 110) & df["age"].notna()).sum()),
        "average spend": round(df["monthly_spend"].mean(), 2),
        "missing spend": int(df["monthly_spend"].isna().sum()),
    }, dtype=object)

print(pd.DataFrame({"before": summary(customers), "after": summary(clean)}))

Two things to notice. Average spend has fallen from over a thousand pounds to a believable figure. And one missing spend value is still there: nobody decided what to do about it, so it was left alone and remains visible. Cleaning means making and recording decisions, not making every gap disappear.

3.8 Cleaning text for AI

Text that will be searched or read by a language model needs its own kind of tidying: stray whitespace, repeated boilerplate such as email signatures, and exact duplicates. The aim is to remove noise without changing meaning.

Python · tidying support messagesimport re

messages = pd.Series([
    "  Where is my   order?\n\nSent from my phone",
    "Where is my order?",
    "REFUND PLEASE!!!   -- \nKind regards, Sam",
    "The board arrived   cracked.\tPlease advise.",
])

def tidy(text):
    text = re.split(r"\n\s*(Sent from my|Kind regards|--)", text)[0]   # cut common sign-offs
    text = re.sub(r"\s+", " ", text).strip()                           # collapse whitespace
    return text.rstrip("- ").strip()

tidied = messages.map(tidy)
print(tidied.tolist())
print("Duplicates after tidying:", int(tidied.str.lower().duplicated().sum()))

Tidying reveals that the first two messages are the same question. Notice what the function does not do: it leaves capital letters and exclamation marks alone. "REFUND PLEASE!!!" tells you something about how the customer feels, and a model can use that.

Cleaning with an AI assistant

AI assistants are good at writing cleaning code and spotting inconsistent categories. Use them to write the rule (a mapping, a regular expression, a function like tidy) which you can read, test and log. Don't paste a table in and ask for it back "cleaned": you can't see what was changed, the result isn't repeatable, and you may be sending personal data to a service that isn't approved for it.

Exercise: clean the churn column safely

Some systems export churn as 'Y', 'N', 'true', 'false', '1' or '0'. Write a function that maps all of these (case-insensitive) to True/False and leaves anything else as missing.

Your turntest_values = pd.Series(["Y", "no", "TRUE", "0", "maybe"])

# Write to_bool(series), apply it to test_values, then press Run
Show a solution
def to_bool(series):
    mapping = {"yes": True, "y": True, "true": True, "1": True,
               "no": False, "n": False, "false": False, "0": False}
    return series.astype(str).str.strip().str.lower().map(mapping)

print(to_bool(pd.Series(["Y", "no", "TRUE", "0", "maybe"])).tolist())
# [True, False, True, False, nan]
Exercise: cap extreme values

Finance confirms that some very high spends are genuine, but you don't want them to dominate an average. Write a function that caps a numeric Series at its 5th and 95th percentiles (winsorising), and compare the mean before and after on spend.

Your turnrng = np.random.default_rng(5)
spend = pd.Series(np.append(rng.normal(40, 12, 196).round(2), [900, 1200, 1500, 2400]))   # 196 ordinary customers, 4 very large ones

# Write cap(series), then press Run
Show a solution
rng = np.random.default_rng(5)
spend = pd.Series(np.append(rng.normal(40, 12, 196).round(2), [900, 1200, 1500, 2400]))   # 196 ordinary customers, 4 very large ones

def cap(series, lower=0.05, upper=0.95):
    lo, hi = series.quantile([lower, upper])
    return series.clip(lo, hi)

print("Mean before:", round(spend.mean(), 2))
print("Mean after: ", round(cap(spend).mean(), 2))
print("Median (unchanged):", spend.median())
# Capping keeps every row but limits the pull of extremes. Log it like any other decision.
steprows affecteddrop exact duplicates1standardise country4set impossible ages to missing2fill missing age with median3convert spend entered in pence1
The decision log from this module's cleaning code. Anyone can now see — and challenge — exactly what changed and why.

Key takeaways

  • Work on a copy; log what, why and how many rows.
  • Map messy categories to standard codes.
  • Ambiguous formats need source knowledge, not guesses.
  • Every missing-value strategy has risks — consider flagging.
  • Fit cleaning statistics on training data only.
  • Measure the same things before and after to prove the cleaning worked.
  • Have AI assistants write cleaning rules you can read and test, not silently edit your data.