Skip to content

26. Data cleaning — Cheat sheet

The essentials of module 26 on one page. Every runnable block on this page is checked against its output. The blocks use this setup:

import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
I want to… Use…
count gaps per column df.isna().sum()
share of gaps per column df.isna().mean()
rows with any gap df.isna().any(axis=1)
see which columns are missing together df[cols].isna().value_counts()
treat - as missing on load read_csv(path, keep_default_na=False, na_values=["", "N/A", "-"])
keep NA and None as real text keep_default_na=False
test for a gap s.isna(), never s == np.nan
count changed cells, ignoring gaps ((before != after) & before.notna()).sum()
drop rows with gaps in some columns df.dropna(subset=["a", "b"])
keep rows with at least k values df.dropna(thresh=k)
fill with a constant s.fillna(0), s.fillna("unknown")
fill with the median s.fillna(s.median())
fill with the median of a group s.fillna(df.groupby(g)[c].transform("median"))
fill from a reference table s.fillna(df[key].map(ref.set_index(key)[c]))
remember what was imputed df[c + "_missing"] = df[c].isna() (before the fill)
fill a time series per entity df.groupby(id)[c].transform(lambda s: s.interpolate())
fill only gaps of at most k readings mask runs longer than k: see Dates and time series gaps
repeat the last known value df.groupby(id)[c].ffill()
count exact duplicates df.duplicated().sum()
see every member of each duplicate group df[df.duplicated(subset=key, keep=False)]
keep the latest version per key df.sort_values(t).drop_duplicates(subset=key, keep="last")
convert price text to numbers pd.to_numeric(s.str.replace(r"[$,]", "", regex=True), errors="coerce")
whole numbers with gaps s.astype("Int64")
strip and collapse spaces s.str.strip().str.replace(r"\s+", " ", regex=True)
unify case s.str.lower(), s.str.title()
map synonyms s.replace({"web": "online"})
unify Unicode accents s.str.normalize("NFC")
check a pattern s.str.fullmatch(r"C\d{5}")
parse one known date format pd.to_datetime(s, format="%d/%m/%Y", errors="coerce")
parse several known formats one to_datetime per format, then combine_first
IQR fences q1, q3 = s.quantile([0.25, 0.75]); q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1)
z-score (s - s.mean()) / s.std()
robust z-score 0.6745 * (s - s.median()) / (s - s.median()).abs().median()
z-score within groups (s - g.transform("mean")) / g.transform("std") with g = s.groupby(key)
cap extreme values s.clip(lower, upper)
range check s.between(1, 50).all()
allowed values s.isin(allowed).all()
orphan foreign keys ~df["store_id"].isin(stores["store_id"])
join status per row df.merge(dim[[key]], on=key, how="left", indicator=True)
collect all rule failures validate(df) -> list[str], then assert not problems, problems
Dtype Gap marker isna() finds it
float64 NaN yes
str (pandas 3 default text) NaN yes
datetime64 NaT yes
Int64, boolean, string pd.NA yes
int64, bool cannot hold a gap; a gap turns them into float64 or object —
s = pd.Series([2.0, np.nan, 4.0])
print(s.isna().sum(), s.count(), len(s)) # gaps, present values, rows
print(s.sum(), s.mean(), s.mean(skipna=False)) # reductions skip NaN by default
print(np.nan == np.nan, pd.isna(np.nan)) # NaN never equals anything
Output
1 2 3
6.0 3.0 nan
False True

read_csv default tokens include "", N/A, NA, n/a, NULL, null, NaN, nan, None, #N/A. They do not include -, ?, unknown, 0 or 999.

Mechanism Gap depends on Dropping rows Good fill
MCAR nothing unbiased, loses data median, group median
MAR other observed columns biased group-wise or model-based fill using those columns
MNAR the missing value itself biased none is safe; collect better data, flag it
Structural a rule (not billed yet, no second address) removes a whole group the rule’s value: 0, "none"
Method Code Bias
Drop rows df.dropna(subset=cols) loses data; biased unless MCAR
Constant fillna(0) wrong unless the gap means 0
Label fillna("unknown") none; keeps rows in groupby
Mean fillna(s.mean()) variance × (nobs−1)/(n−1)(n_\text{obs}-1)/(n-1); correlations toward 0
Median fillna(s.median()) shrinks the spread too, and shifts the mean on skewed data; robust to outliers
Group median fillna(df.groupby(g)[c].transform("median")) smaller error; filled values sit on group centers
Forward fill groupby(id)[c].ffill() stale values over long gaps
Backward fill groupby(id)[c].bfill() reads the future: fine for batch history, leakage in forecasts and live alerts
Linear interpolation groupby(id)[c].transform(lambda s: s.interpolate()) smooths away spikes inside gaps; reads the next value, so it leaks in forecasts
Time interpolation s.interpolate(method="time") on a DatetimeIndex as linear, weighted by real time gaps
Indicator df[c + "_missing"] = df[c].isna() none itself, but it does not undo the bias of the fill; add it with any fill
lot = pd.Series([4000.0, np.nan, 9000.0, np.nan, 5000.0])
area = pd.Series(["Downtown", "Downtown", "Lakeview", "Lakeview", "Lakeview"])
print(lot.fillna(lot.median()).tolist())
print(lot.fillna(lot.groupby(area).transform("median")).tolist())
print(round(lot.std(), 1), round(lot.fillna(lot.mean()).std(), 1)) # spread shrinks
Output
[4000.0, 5000.0, 9000.0, 5000.0, 5000.0]
[4000.0, 4000.0, 9000.0, 7000.0, 5000.0]
2645.8 1870.8

Score a fill on values you hide on purpose: hide known values with rng.choice(known, size=k, replace=False), fill, and compare with the truth (MAE).

interpolate(limit=k) caps how many cells it fills per gap, but it still fills part of a long gap. To leave long gaps empty, count each gap run:

def fill_short_gaps(s: pd.Series, max_gap: int = 3) -> pd.Series:
gap = s.isna()
run = gap.groupby((~gap).cumsum()).transform("sum") # length of each gap run
return s.interpolate(limit_direction="both").mask(gap & (run > max_gap))
demo = pd.Series([1.0, np.nan, 3.0] + [np.nan] * 7 + [11.0])
print(demo.interpolate(limit=3).tolist())
print(fill_short_gaps(demo).tolist())
Output
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, nan, nan, nan, nan, 11.0]
[1.0, 2.0, 3.0, nan, nan, nan, nan, nan, nan, nan, 11.0]

Per entity: df.groupby(id)[cols].transform(fill_short_gaps).

Call Marks or keeps
df.duplicated() rows equal to an earlier row in every column
df.duplicated(subset=key) rows whose key appeared before
keep="first" / "last" / False leave the first / last copy unmarked / mark every copy
df.drop_duplicates(subset=key, keep="last") one row per key, the last one in table order
df.loc[df.groupby(key)[t].idxmax()] one row per key, the latest by time t

Order: normalize text → drop exact duplicates → check the key with duplicated(subset=key, keep=False) → decide per group.

price_text = pd.Series(["$79.99", "$1,299.00", None])
price = pd.to_numeric(price_text.str.replace(r"[$,]", "", regex=True), errors="coerce")
print(price.tolist(), price_text.isna().sum() == price.isna().sum()) # no new gaps
flags = pd.Series(["yes", "no", "yes"]).map({"yes": True, "no": False})
print(flags.dtype, pd.Series([3, None], dtype="Int64").tolist())
region = pd.Series([" north", "NORTH ", "N."])
print(region.str.strip().str.title().replace({"N.": "North"}).tolist())
Output
[79.99, 1299.0, nan] True
bool [3, <NA>]
['North', 'North', 'North']
Pattern Code
strip, coerce, count new gaps n0 = s.isna().sum(); convert; assert out.isna().sum() == n0
list values that are not allowed s[s.notna() & ~s.isin(allowed)].unique()
show hidden spaces s.map(repr)
$ as a plain character regex=False, or a class [$]
Situation Use
one known format pd.to_datetime(s, format="%Y-%m-%d")
ISO dates with or without times format="ISO8601"
several known formats per-format parse with errors="coerce", then combine_first
count formats first s.str.fullmatch(r"\d{2}/\d{2}/\d{4}").sum()
check a parse rule from another column, such as dates rising with an id
mixed = pd.Series(["2023-01-07", "07/01/2023", "January 7, 2023"])
trap = pd.to_datetime(mixed, format="mixed", dayfirst=True) # swaps the ISO date
parsed = None
for fmt in ["%Y-%m-%d", "%d/%m/%Y", "%B %d, %Y"]:
part = pd.to_datetime(mixed, format=fmt, errors="coerce")
parsed = part if parsed is None else parsed.combine_first(part)
print(trap.dt.strftime("%Y-%m-%d").tolist())
print(parsed.dt.strftime("%Y-%m-%d").tolist(), parsed.isna().sum())
Output
['2023-07-01', '2023-01-07', '2023-01-07']
['2023-01-07', '2023-01-07', '2023-01-07'] 0

Format codes: %Y 2023, %m 01, %d 07, %B January, %b Jan, %H:%M:%S 14:05:00.

Rule Formula Strength Weakness
Range rule ~s.between(lo, hi) exact for known business limits needs domain knowledge
IQR (Tukey) outside Q1−1.5 IQRQ_1 - 1.5\,\text{IQR} … Q3+1.5 IQRQ_3 + 1.5\,\text{IQR} not moved by extremes flags skewed tails; useless on small counts
z-score ∣(x−xˉ)/s∣>3\lvert (x - \bar{x}) / s \rvert > 3 simple masking: big errors inflate ss
Robust z 0.6745 ∣x−med∣/MAD>3.50.6745\,\lvert x - \text{med} \rvert / \text{MAD} > 3.5 not moved by extremes MAD can be 0
Group residual z z-score of the residual from a per-group fit of log(price) on log(size) uses context needs enough rows per group
Robust z rule flag ∣zrobust∣>3.5\lvert z^\text{robust} \rvert > 3.5 (Iglewicz–Hoaglin) standard threshold —
Rolling residual x - x.rolling(7, center=True).median() follows trends and cycles needs ordered data; center=True reads the future, so use a trailing window for live alerts
units = pd.Series([1, 1, 2, 1, 3, 2, 1, 999, -2, 1])
q1, q3 = units.quantile([0.25, 0.75])
print(units[~units.between(q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1))].tolist())
z = (units - units.mean()) / units.std()
print(units[z.abs() > 3].tolist()) # n = 10: |z| can never exceed 9 / sqrt(10) = 2.85
print(units.clip(1, 50).tolist()) # cap to the valid range
Output
[999, -2]
[]
[1, 1, 2, 1, 3, 2, 1, 50, 1, 1]
Action When
Repair another trusted column gives the true value
Flag not sure; let people and later steps decide
Cap (clip, winsorize) extremes distort means or linear models
Remove proven error that cannot be repaired
def validate(df: pd.DataFrame) -> list[str]:
problems = []
if df["order_id"].isna().any():
problems.append("order_id: missing")
if df.duplicated(subset=["order_id", "product_id"]).any():
problems.append("key: duplicates")
if not df["quantity"].between(1, 50).all():
problems.append("quantity: outside 1..50")
return problems
lines = pd.DataFrame(
{"order_id": ["O1", "O1"], "product_id": ["P1", "P1"], "quantity": [2, 0]}
)
print(validate(lines))
Output
['key: duplicates', 'quantity: outside 1..50']
Rule type Example
not null df[c].notna().all()
unique key not df.duplicated(subset=key).any()
range df[c].between(lo, hi).all()
allowed values df[c].isin(allowed).all()
pattern df[c].str.fullmatch(regex).all()
cross-column np.isclose(price * qty * (1 - disc), revenue, atol=0.01).all()
referential integrity df[fk].isin(dim[pk]).all()

Cleaning log: one record per step with the step name, rows in, rows out and cells or rows changed. Build it in the loop that runs the steps, print it with pd.DataFrame(log).to_string(index=False) and save it next to the clean file.

  • NaN == NaN is False, and NaN != NaN is True. Use isna(), and mask gaps out of change counts.
  • read_csv turns the text NA and None into gaps by default. Use keep_default_na=False with your own na_values.
  • One unknown token such as - makes a number column load as str.
  • errors="coerce" hides every value it cannot read. Count gaps before and after.
  • str.replace("$", "", regex=True) removes nothing: $ is the end anchor.
  • format="mixed", dayfirst=True reads 2023-01-07 as July 1 in pandas 3, with no warning. A parse with no NaT can still be wrong.
  • groupby drops rows whose key is NaN. Label the gaps or pass dropna=False.
  • interpolate() on a table that interleaves several sensors mixes them. Group first.
  • bfill, interpolation, limit_direction="both" and centered windows read values after the gap. Fine for cleaning history; in forecasting or live detection use ffill and trailing windows.
  • interpolate(limit=3) does not skip long gaps: pandas 3.1 fills the first 3 cells of a longer gap (3 from each end with limit_direction="both"). Measure gap runs and mask the long ones.
  • With the sample standard deviation, ∣z∣≤(n−1)/n\lvert z \rvert \le (n-1)/\sqrt{n}. On 10 values, |z| > 3 never fires.
  • Missingness looks random by eye more often than it is. Compare groups against chance with a permutation check.
  • The IQR rule on small integer counts flags normal values; prefer business ranges.
  • The z-score is masked by the errors it should find. Use IQR or a robust z-score.
  • Any global rule on skewed data flags the genuine tail. Use log scale and groups, and flag before you delete.
  • Fit everything learned from many rows on training rows only: fill values, group medians, IQR fences, z parameters, clip limits. Row-local fixes (types, text, dates, lookups) are safe before the split. Drop exact duplicates before the split.
  • Create the indicator column before the fill; afterwards there are no gaps to mark.
  • Validate a validator: break a copy on purpose and check that each rule fires.