Valid Ranges and Category Names
Once types and units are right, two kinds of wrong values remain: numbers outside what is physically or logically possible (an age of 230, a negative price, a discharge date before the admission date) and many spellings of one category ("Hanoi", "Ha Noi", "HN", "hanoi "). Both are fixed with rules written down in advance: a schema of allowed ranges and values, and a mapping from spellings to canonical names.
This is different from outlier handling. An outlier is unusual but possible (a 105-year-old patient, a very large order); Outlier Detection finds those, and you usually keep them. A value outside the valid range is impossible, so it is an error to correct or to turn into a missing value.
A range schema
Write the rules as data, not as scattered if statements. Each rule says what is allowed and what to do with a violation:
| Column | Allowed | On violation |
|---|---|---|
age |
0 to 120 | set missing (impossible value) |
heart_rate |
20 to 250 | set missing |
discount |
0 to 1 | values 1 to 100 are percentages: divide by 100; otherwise missing |
quantity |
integer, at least 1 | drop the row (an order line without items is not an order line) |
discharged |
on or after admitted |
set missing and flag for review |
import numpy as np
import pandas as pd
visits = pd.DataFrame({
"age": [34, 230, 51, -1, 47, 88],
"heart_rate": [72, 80, 0, 64, 310, 58],
"discount": [0.1, 15, 0.0, 0.25, 250, 0.05],
"quantity": [1, 2, 0, 3, 1, 1],
"admitted": pd.to_datetime(["2026-01-03", "2026-01-05", "2026-01-07", "2026-01-08", "2026-01-09", "2026-01-10"]),
"discharged": pd.to_datetime(["2026-01-05", "2026-01-04", "2026-01-09", "2026-01-12", "2026-01-11", "2026-01-15"]),
})
ranges = {"age": (0, 120), "heart_rate": (20, 250)}
log = []
clean = visits.copy()
for col, (lo, hi) in ranges.items():
bad = ~clean[col].between(lo, hi)
log.append(f"{col}: {int(bad.sum())} outside [{lo}, {hi}] -> missing {clean.loc[bad, col].tolist()}")
clean[col] = clean[col].where(~bad).astype("Float64")
pct = clean["discount"].between(1, 100, inclusive="right")
clean.loc[pct, "discount"] = clean.loc[pct, "discount"] / 100
bad = ~clean["discount"].between(0, 1)
log.append(f"discount: {int(pct.sum())} percent -> share, {int(bad.sum())} impossible -> missing")
clean["discount"] = clean["discount"].where(~bad)
order = clean["discharged"] < clean["admitted"]
log.append(f"discharged before admitted: {int(order.sum())} -> missing, flagged")
clean["review"] = order
clean.loc[order, "discharged"] = pd.NaT
zero_qty = clean["quantity"] < 1
log.append(f"quantity < 1: {int(zero_qty.sum())} rows dropped")
clean = clean[~zero_qty]
print("\n".join(log))
print(clean.drop(columns="admitted").to_string())age: 2 outside [0, 120] -> missing [230, -1]
heart_rate: 2 outside [20, 250] -> missing [0, 310]
discount: 1 percent -> share, 1 impossible -> missing
discharged before admitted: 1 -> missing, flagged
quantity < 1: 1 rows dropped
age heart_rate discount quantity discharged review
0 34.0 72.0 0.10 1 2026-01-05 False
1 <NA> 80.0 0.15 2 NaT True
3 <NA> 64.0 0.25 3 2026-01-12 False
4 47.0 <NA> NaN 1 2026-01-11 False
5 88.0 58.0 0.05 1 2026-01-15 False
Every violation is now either corrected by a documented rule (15 → 0.15) or turned into a missing value that the imputation step will handle, and the log says how many rows each rule touched. Notice that -1 for age is caught by the same range check: it is a placeholder for "unknown", and it ends up as a missing value, which is what it meant.
Tip: Libraries such as
panderaor Great Expectations turn a schema like this into reusable validation with reports. They are not in the browser runtime, but the idea is exactly this table: rules as data, checked on every new batch, and a failing batch stops the pipeline.
Clipping is not cleaning
Replacing values above a limit with the limit (clip, "winsorising") is a modelling choice for valid but extreme values: it reduces their pull on a linear model. Using it to hide impossible values turns an age of 230 into a confident 120, a value that looks real and is wrong. Make impossible values missing; clip only valid extremes, and fit the clipping limits (for example the 1st and 99th percentiles) on the training data only.
Category names: normalise, then map
Text categories drift: capitals, extra spaces, accents, abbreviations, typos. Clean them in two stages:
- Mechanical normalisation, the same for every column: strip, lower-case, collapse whitespace, remove accents.
- A mapping from known variants to canonical names, reviewed by someone who knows the domain. Unknown variants are reported, never guessed.
import unicodedata
import pandas as pd
cities = pd.Series(["Hanoi", " ha noi", "HN", "Hà Nội", "Ho Chi Minh City", "HCMC",
"Saigon", "hcm", "Da Nang", "Đà Nẵng", "Danang", "Hue", "Hanoi City"])
def normalise(s):
s = unicodedata.normalize("NFKD", s.replace("Đ", "D").replace("đ", "d"))
s = "".join(ch for ch in s if not unicodedata.combining(ch))
return " ".join(s.lower().split())
canonical = {
"hanoi": "Hanoi", "ha noi": "Hanoi", "hn": "Hanoi",
"ho chi minh city": "Ho Chi Minh City", "hcmc": "Ho Chi Minh City",
"saigon": "Ho Chi Minh City", "hcm": "Ho Chi Minh City",
"da nang": "Da Nang", "danang": "Da Nang",
}
norm = cities.map(normalise)
mapped = norm.map(canonical)
print("distinct spellings:", cities.nunique(), "-> after normalising:", norm.nunique(),
"-> after mapping:", mapped.nunique())
print("not in the mapping:", sorted(norm[mapped.isna()].unique()))
print(mapped.value_counts().to_dict())distinct spellings: 13 -> after normalising: 11 -> after mapping: 3
not in the mapping: ['hanoi city', 'hue']
{'Hanoi': 4, 'Ho Chi Minh City': 4, 'Da Nang': 3}
Thirteen spellings collapse to three cities, and two values are reported instead of guessed: hue is a real city that is simply missing from the mapping, and hanoi city is a variant someone should add. Fuzzy matching (edit distance) can suggest mappings for review, but applied automatically it merges things that only look alike: "Austria" and "Australia" differ by two letters.
Rare and unknown categories
After mapping, some categories are still rare (a city with 2 rows) or appear only in new data. Do not drop them in cleaning. Decide in the encoding step, where OneHotEncoder(handle_unknown="infrequent_if_exist", min_frequency=...) groups them, fitted on the training data.
Pitfalls
- Fixing impossible values with the column mean: first make them missing, then let a fitted imputer decide; the mean of the whole dataset leaks test information anyway.
- Ranges derived from the data: "valid = within 3 standard deviations" is outlier detection, not validation. Valid ranges come from physics, law, business rules and documentation.
- Lower-casing values whose case matters: product codes
"A1"and"a1"may be different products. Normalise only what you know is case-insensitive. - Silent
map: values missing from the mapping becomeNaN. Always print what did not map.
Practice
- A
temperature_ccolumn for a cold-storage warehouse contains values between −30 and 8, plus a few values of 85. What do you check before setting them missing?
Answer
Whether 85 could be a unit problem (85 °F is about 29 °C, still impossible for cold storage, so probably not) or a sensor error code (many devices emit a fixed value such as 85 °C on a read failure; the DS18B20 sensor is a known example). If it is an error code, map it to missing and log the rule with the device documentation.
- Why is
"Austria"→"Australia"a risk with automatic fuzzy matching, and what would you do instead?
Answer
Two different valid categories are close in edit distance, so a "closest match" rule merges them. Use fuzzy matching only to propose candidate mappings, have a person approve them into the mapping table, and keep reporting unmapped values.
Test yourself
What distinguishes an invalid value from an outlier?
- Invalid values are larger
- An invalid value is impossible by definition (rules, physics, documentation); an outlier is unusual but possible
- Outliers are always errors
- There is no difference
An age of 230 appears. Which fix is right during cleaning?
- Clip it to 120
- Replace it with the column mean of the whole dataset
- Make it missing, log it, and let the fitted imputer handle it later
- Leave it
After normalising and mapping city names, norm.map(canonical) gives NaN for some rows. What should the script do?
- Drop those rows
- Fill them with the most common city
- Report the unmapped values so someone extends the mapping
- Fuzzy-match them automatically