Skip to content

26. Data cleaning

Real data arrives broken. A point-of-sale export writes prices as text, spells one region five ways, repeats rows and mixes three date formats. A model or a report built on that table gives wrong numbers, and nothing warns you. Data cleaning is the work that finds these problems, fixes or labels them, and proves that the result is correct.

This module cleans data/sales_raw.csv from start to finish, one step at a time. Every count is checked against the course data dictionary. Then it handles gaps in customer, house and sensor data, and measures the bias that each fill method adds. The module ends with validation checks and a cleaning log, so that you can rerun the whole pipeline tomorrow on a new export.

  • Profile a raw file and find hidden problems: missing-value tokens such as -, text in number columns, inconsistent spellings and impossible values.
  • Explain why values are missing (MCAR, MAR, MNAR, structural) and choose between dropping and imputing: constant, mean, median, group-wise median, forward fill and interpolation, with the bias each one adds.
  • Find and remove exact and key-based duplicates with duplicated and drop_duplicates (subset, keep).
  • Fix types, normalize messy text with the .str accessor and parse mixed date formats safely in pandas 3.
  • Detect outliers with the IQR rule and z-scores, compare them, and decide whether to remove, cap or flag.
  • Write validation checks (ranges, uniqueness, allowed values, referential integrity) as a validate(df) -> list[str] function and keep a cleaning log of what each step changed.

Every pandas block on this page runs after this setup block. It fixes how pandas prints tables:

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)

Data quality is how well a dataset fits the job you use it for. Analysts split it into a few quality dimensions. Each dimension is a question you can test with code:

Dimension Question A failure in data/sales_raw.csv
Completeness Are the values present? 23 order lines have no customer_id
Validity Does each value have the right type and range? unit_price is text such as $79.99; a quantity of -3
Uniqueness Is each real-world thing stored once? 36 rows are exact copies of other rows
Consistency Is the same fact written the same way? North, north, NORTH and North
Accuracy Is the value true? a quantity of 999 units of a 4K TV

Data cleaning is the process that measures these dimensions, fixes what it can, labels what it cannot fix and records every change. It is not a one-off edit in a spreadsheet. It is code that you run again on every new export.

A cleaning pipeline is a script that turns the raw file into the clean file in fixed steps. Four rules make it trustworthy:

  1. Never edit the raw file. Read it, clean a copy in memory and write the result to a new file. The raw file is your evidence.
  2. One step, one job. Fix types, then text, then dates, then duplicates and so on. Each step is small enough to test.
  3. Count every change. Each step reports how many rows or cells it changed. A cleaning log is the table of these counts. It tells a reviewer what happened to the data.
  4. Validate at the end. Rules that the clean table must satisfy run as code. If one fails, the pipeline stops before anyone uses bad data.
flowchart LR
    R["raw CSV<br/>(read-only)"] --> P["profile"]
    P --> T["fix types<br/>and text"]
    T --> D["parse dates"]
    D --> U["remove<br/>duplicates"]
    U --> M["repair and<br/>fill gaps"]
    M --> O["flag<br/>outliers"]
    O --> V{"validate"}
    V -- "problems" --> P
    V -- "no problems" --> C["clean file<br/>+ cleaning log"]

The order matters. Normalize text before you look for duplicates, because North and north hide a duplicate. Convert types before you check ranges, because a range check on text compares letters, not numbers.

A missing value is a cell with no known value. pandas marks it with a special marker that depends on the dtype:

Dtype Missing marker Example
float64 NaN (not a number, from module 09) a blank lot_sqft
str (pandas 3 default for text) NaN a blank region
datetime64 NaT (not a time) a date that could not be parsed
nullable Int64, boolean, string pd.NA a count with a gap

One test finds all of them: isna() returns True for every missing cell, and notna() is its opposite.

readings = pd.Series([21.4, None, 22.9, np.nan])
labels = pd.Series(["ok", None, "warn"])
dates = pd.to_datetime(pd.Series(["2024-05-01", None]))
counts = pd.Series([3, None], dtype="Int64")
print(readings.isna().tolist(), labels.isna().tolist())
print(dates.isna().tolist(), counts.isna().tolist())
print(readings.dtype, labels.dtype, dates.dtype, counts.dtype)
Output
[False, True, False, True] [False, True, False]
[False, True] [False, True]
float64 str datetime64[us] Int64

pandas converts None to the marker of the column. A plain integer column cannot hold NaN, so pd.Series([3, None]) becomes float64. The nullable dtype Int64 (capital I) keeps whole numbers and stores the gap as pd.NA.

Three rules about missing values save you from silent mistakes:

print(np.nan == np.nan)
print(readings.sum(), readings.mean(), readings.count(), len(readings))
print(readings.mean(skipna=False))
Output
False
44.3 22.15 2 4
nan
  • NaN is not equal to anything, not even itself. Never test x == np.nan. Use isna().
  • sum(), mean() and most other reductions skip missing values by default. The mean above is the mean of two values, not four.
  • count() counts the values that are present. len() counts all rows. Their difference is the number of gaps.

A CSV file has no NaN. A system writes a gap as some text: an empty field, N/A, NULL, - or ?. read_csv turns a fixed list of these missing-value tokens into NaN. The list includes "", N/A, NA, n/a, NULL, null, NaN, nan and None. It does not include -, ?, unknown or 0.

Two options control the list:

  • na_values=["-", "?"] adds tokens to the default list.
  • keep_default_na=False switches the default list off. Then only your na_values count as missing.

The default list can be too generous. In this small file, NA is the code for North America and None is a real product name:

import io
csv_text = "store,continent,product\nS01,NA,None\nS02,EU,-\n"
default = pd.read_csv(io.StringIO(csv_text))
strict = pd.read_csv(
io.StringIO(csv_text), keep_default_na=False, na_values=["", "-"]
)
print(default)
print(strict)
Output
store continent product
0 S01 NaN NaN
1 S02 EU -
store continent product
0 S01 NA None
1 S02 EU NaN

io.StringIO wraps a string so that read_csv can read it like a file. The default settings lose two real values and keep the -. The strict settings keep NA and None and treat only empty fields and - as missing. Write the tokens of your source system into the pipeline on purpose. data/config.json does this with "na_values": ["", "N/A", "-"].

The right fix depends on why a value is missing. Statisticians name three missing-data mechanisms, and practice adds a fourth case:

Mechanism Meaning Example Effect of dropping rows
MCAR (missing completely at random) the gap has nothing to do with any value lot_sqft blanks in data/houses.csv were removed at random fewer rows, no bias
MAR (missing at random) the gap depends on other columns you observe younger survey respondents skip the income question more often bias, unless you use the related columns
MNAR (missing not at random) the gap depends on the missing value itself people with very high incomes skip the income question bias that the data alone cannot fix
Structural the value does not exist yet, or is 0 by definition total_charges is blank for customers with 0 months of tenure a whole group disappears

You can never prove MCAR from the data. You can collect evidence: compare the rows with gaps and the rows without gaps. Two random subsets always differ a little, so the question is whether they differ by more than chance. A permutation check answers it: shuffle the gap mask many times, compute the same difference each time, and see how often chance alone gives a difference as large as the real one. Example 6 runs one. Module 29 covers formal tests.

You have three options for a gap: drop the row, drop the column or impute it, which means to fill it with an estimated value. Each option changes the data in its own way:

Method pandas Good for Bias it adds
Drop rows df.dropna(subset=[...]) few MCAR gaps removes groups that are often missing
Drop a column df.drop(columns=...) a column that is mostly empty loses a feature
Constant fillna(0), fillna("unknown") structural gaps, labels wrong if the gap is not really 0
Mean fillna(s.mean()) symmetric data shrinks the spread; pulled by outliers
Median fillna(s.median()) skewed data shrinks the spread
Group-wise median fillna(df.groupby(g)[c].transform("median")) values that depend on a group smaller; still shrinks the spread inside each group
Forward fill ffill() slowly changing states repeats stale values over long gaps
Interpolation interpolate() smooth time series smooths away real spikes
Indicator column df[c].isna() as a new column any imputation none itself; it keeps the fact of missingness but does not undo the bias of the fill

Mean imputation shrinks the spread by an exact amount. Every filled value sits on the mean, so it adds nothing to the sum of squared distances. With nn rows, of which nobsn_\text{obs} have a value, the sample variance after the fill is:

sfilled2=nobs−1n−1 sobs2s^2_\text{filled} = \frac{n_\text{obs} - 1}{n - 1}\, s^2_\text{obs}

With 3% missing, the variance drops by about 3%. Correlations with other columns shrink too, because the filled values do not move with them. Example 6 measures the spread, and exercise M26-C13 measures the correlation.

A duplicate is a row that records the same real-world event as another row. There are three kinds:

  • An exact duplicate has the same value in every column. An export that ran twice creates them.
  • A key duplicate has the same primary key but different values elsewhere. A primary key is the column, or set of columns, that must identify each row uniquely. In the sales data it is (order_id, product_id).
  • A near duplicate differs only by formatting, such as North and north. It becomes an exact duplicate after you normalize the text.

duplicated() marks duplicates, and drop_duplicates() removes them. Both take subset (the columns to compare) and keep (which copy is not marked):

orders = pd.DataFrame(
{
"order_id": ["O1", "O1", "O2", "O2"],
"product_id": ["P001", "P001", "P003", "P003"],
"region": ["West", "West", "east", "East"],
}
)
print(orders.duplicated().tolist())
print(orders.duplicated(subset=["order_id", "product_id"]).tolist())
print(orders.duplicated(subset=["order_id", "product_id"], keep=False).tolist())
print(len(orders.drop_duplicates(subset=["order_id", "product_id"], keep="last")))
Output
[False, True, False, False]
[False, True, False, True]
[True, True, True, True]
2
keep= Marks Use it to
"first" (default) every copy except the first keep the oldest row
"last" every copy except the last keep the latest correction
False every copy look at all rows of each duplicate group

The O2 rows differ only in the case of region, so the exact test misses them. The key test finds them. Always check the primary key after you drop exact duplicates.

A type fix gives a column the dtype that its meaning needs: numbers for prices, dates for dates and a small set of labels for categories. Module 24 introduced pd.to_numeric and astype. In a cleaning pipeline, use them with a strict pattern:

  1. Remove the known junk, such as $ and thousands separators.
  2. Convert with errors="coerce", which turns every value that still fails into NaN.
  3. Count the gaps before and after. New gaps are values that the step could not read. Look at them before you go on.
price_text = pd.Series(["$79.99", "$1,299.00", None, "79,99"])
price = pd.to_numeric(price_text.str.replace(r"[$,]", "", regex=True), errors="coerce")
print(price.tolist())
print("gaps before:", price_text.isna().sum(), "after:", price.isna().sum())
Output
[79.99, 1299.0, nan, 7999.0]
gaps before: 1 after: 1

The regular expression [$,] matches a dollar sign or a comma. The last value uses a comma as the decimal mark, so removing commas turns 79,99 into 7999. The gap count does not catch it, because the result is a valid number. That is why a range check comes later in the pipeline.

Other common fixes:

Raw values Fix Result dtype
"yes", "no" s.map({"yes": True, "no": False}) bool (or object if a value is not in the dict)
whole numbers with gaps s.astype("Int64") nullable Int64
a few repeated labels s.astype("category") category
"2024-05-01" pd.to_datetime(s, format="%Y-%m-%d") datetime64

Text columns collect invisible differences: spaces at the ends, double spaces inside, different case and different spellings of one value. Text normalization rewrites every value to one canonical form, a single agreed spelling. The .str accessor applies a string method to every value of a column and skips the gaps:

region = pd.Series([" North ", "north", "NORTH", "North ", None, "N."])
step1 = region.str.strip()
step2 = step1.str.title()
step3 = step2.replace({"N.": "North"})
print(step3.tolist())
print(step3.value_counts(dropna=False).to_dict())
Output
['North', 'North', 'North', 'North', nan, 'North']
{'North': 5, nan: 1}
Problem Fix
spaces at the ends .str.strip()
double spaces inside .str.replace(r"\s+", " ", regex=True)
mixed case .str.lower(), .str.title() or .str.upper()
synonyms and abbreviations .replace({"N.": "North"}) with a mapping dict
unknown spellings left over ~s.isin(allowed) to list them
a fixed pattern, such as an id .str.fullmatch(r"C\d{5}") to validate

Normalize first, then check the result against the list of allowed values. A value that is still not allowed needs a human decision, not a guess.

pd.to_datetime turns text into datetime64. Give it an explicit format whenever you know it. The format codes come from module 09: %Y year, %m month, %d day, %B month name.

When one column mixes formats, pandas (since version 2.0) offers format="mixed", which guesses the format of each value on its own. Guessing is dangerous with day-first dates. 07/01/2023 is 7 January in Europe and July 1 in the United States. The option dayfirst=True says “prefer the day first”. Check what it does to ISO dates:

mixed = pd.Series(["2023-01-07", "07/01/2023", "January 7, 2023"])
guess = pd.to_datetime(mixed, format="mixed")
guess_dayfirst = pd.to_datetime(mixed, format="mixed", dayfirst=True)
print(guess.dt.strftime("%Y-%m-%d").tolist())
print(guess_dayfirst.dt.strftime("%Y-%m-%d").tolist())
Output
['2023-01-07', '2023-07-01', '2023-01-07']
['2023-07-01', '2023-01-07', '2023-01-07']

All three strings mean 7 January 2023. Without dayfirst, pandas reads 07/01/2023 as July 1. With dayfirst=True, it fixes that value but now reads the ISO date 2023-01-07 as July 1. No setting of format="mixed" reads this column correctly, and neither run raises an error or a warning.

The safe method parses each known format on its own and combines the results:

iso = pd.to_datetime(mixed, format="%Y-%m-%d", errors="coerce")
day_first = pd.to_datetime(mixed, format="%d/%m/%Y", errors="coerce")
month_name = pd.to_datetime(mixed, format="%B %d, %Y", errors="coerce")
parsed = iso.combine_first(day_first).combine_first(month_name)
print(parsed.dt.strftime("%Y-%m-%d").tolist())
Output
['2023-01-07', '2023-01-07', '2023-01-07']

Each call parses only the values that match its format exactly and gives NaT for the rest. a.combine_first(b) keeps the values of a and takes b where a is missing. A value that matches no format stays NaT, so you can count and inspect it.

Situation Use
one known format pd.to_datetime(s, format="%d/%m/%Y")
ISO 8601 only, with or without times pd.to_datetime(s, format="ISO8601")
a few known formats one to_datetime per format with errors="coerce", then combine_first
unknown formats, quick exploration format="mixed", then check the result against another column

An outlier is a value far from the other values. It is one of two things:

  • an error: a typo, a wrong unit or a broken sensor, such as a quantity of 999;
  • a genuine extreme: a rare but real value, such as a 3.7-million-dollar lakeside house.

Statistics can find unusual values. Only domain knowledge can say which kind they are. Three rules are common.

The IQR rule (also called Tukey’s fences) uses quartiles. The interquartile range (IQR) is Q3−Q1Q_3 - Q_1, the width of the middle half of the data. A value is an outlier when it lies outside the fences:

lower=Q1−1.5⋅IQR,upper=Q3+1.5⋅IQR\text{lower} = Q_1 - 1.5 \cdot \text{IQR}, \qquad \text{upper} = Q_3 + 1.5 \cdot \text{IQR}

The z-score of a value says how many standard deviations it lies from the mean. A common rule flags ∣z∣>3|z| > 3:

zi=xi−xˉsz_i = \frac{x_i - \bar{x}}{s}

The robust z-score replaces the mean with the median and the standard deviation with the MAD (median absolute deviation: the median of ∣xi−median∣|x_i - \text{median}|). The factor 0.6745 makes it comparable to a normal z-score:

zirobust=0.6745⋅xi−medianMADz^\text{robust}_i = 0.6745 \cdot \frac{x_i - \text{median}}{\text{MAD}}

The usual rule (Iglewicz and Hoaglin) flags ∣zirobust∣>3.5|z^\text{robust}_i| > 3.5.

units = pd.Series([1, 1, 2, 1, 3, 2, 1, 999, -2, 1])
q1, q3 = units.quantile([0.25, 0.75])
iqr = q3 - q1
iqr_flag = (units < q1 - 1.5 * iqr) | (units > q3 + 1.5 * iqr)
z = (units - units.mean()) / units.std()
print("fences:", q1 - 1.5 * iqr, q3 + 1.5 * iqr)
print("IQR flags:", units[iqr_flag].tolist())
print("z-scores:", z.round(2).tolist())
Output
fences: -0.5 3.5
IQR flags: [999, -2]
z-scores: [-0.32, -0.32, -0.31, -0.32, -0.31, -0.31, -0.32, 2.85, -0.33, -0.32]

The IQR rule uses quartiles, which one extreme value cannot move, so it finds both bad values. The z-score of 999 is only 2.85. On 10 values that is not a surprise: with the sample standard deviation, no value among nn can have ∣z∣|z| above (n−1)/n(n-1)/\sqrt{n}, which is 2.85 for n=10n = 10. So the rule ∣z∣>3|z| > 3 can never fire on 10 values. Even without the 999, -2 has a z-score of about −2.4, inside the limit.

On a larger sample, the z-score works for one big error but fails for several. Large errors inflate the mean and the standard deviation, so they hide each other. This effect is called masking:

rng = np.random.default_rng(42)
counts = pd.Series(rng.integers(1, 4, size=200))
for errors in [[999], [999, 1000, 500, 250]]:
s = counts.copy()
s.iloc[: len(errors)] = errors
z = (s - s.mean()) / s.std()
q1, q3 = s.quantile([0.25, 0.75])
n_iqr = (~s.between(q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1))).sum()
n_z = (z.abs() > 3).sum()
print(f"{len(errors)} error(s): z > 3 flags {n_z}, IQR flags {n_iqr}")
print(" z of the errors:", z.iloc[: len(errors)].round(2).tolist())
Output
1 error(s): z > 3 flags 1, IQR flags 1
z of the errors: [14.07]
4 error(s): z > 3 flags 3, IQR flags 4
z of the errors: [9.22, 9.23, 4.54, 2.2]

With one error, its z-score is far above 3. With four, the standard deviation grows so much that 250, a value 100 times the typical count, gets a z-score near 2. The IQR rule still flags all four.

IQR rule z-score Robust z-score
Center and spread median area, IQR mean, standard deviation median, MAD
Moved by the outliers themselves no yes (masking) no
Assumes nothing about the shape roughly normal data roughly symmetric data
On right-skewed data (prices, incomes) flags many genuine high values flags many genuine high values flags many genuine high values
On small integer counts IQR can be 0 or 1, so it flags normal values fine if there are no huge errors MAD can be 0, so it fails

On skewed data, apply the rule to the log of the values, or within groups, or both. Then decide what to do with each flagged value:

Action pandas Use when
Remove df[~flag] the value is a proven error and cannot be repaired
Cap (winsorize) s.clip(lower, upper) errors and extremes distort a mean or a linear model
Flag df["price_suspect"] = flag you are not sure; let later steps and people decide
Repair recompute from other columns another trusted column holds the true value

Winsorizing replaces values beyond a limit with the limit itself, so the row stays but its influence shrinks.

A validation check is a rule that the data must satisfy, written as code. Module 06 used assert for checks inside a program. A data pipeline needs more than one assert, because the first failure stops the script and hides the other problems. A better pattern collects every problem in a list:

def check_units(units: pd.Series) -> list[str]:
problems = []
if units.isna().any():
problems.append(f"{units.isna().sum()} missing quantities")
out_of_range = ~units.between(1, 50)
if out_of_range.any():
problems.append(f"{out_of_range.sum()} quantities outside 1..50")
return problems
print(check_units(units))
print(check_units(pd.Series([1, 2, 3])))
Output
['2 quantities outside 1..50']
[]

An empty list means “no problems”. The pipeline then ends with one line: assert not problems, problems. Typical checks:

Check Example rule pandas
Not null every line has an order_id df["order_id"].notna().all()
Range quantity is 1 to 50 df["quantity"].between(1, 50).all()
Allowed values discount is 0, 0.05, 0.1 or 0.2 df["discount"].isin([0, 0.05, 0.1, 0.2]).all()
Uniqueness (order_id, product_id) is unique not df.duplicated(subset=key).any()
Pattern ids look like C00001 df["customer_id"].str.fullmatch(r"C\d{5}").all()
Cross-column rule revenue = price × quantity × (1 − discount) np.isclose(...) with a tolerance
Referential integrity every store_id exists in stores.csv df["store_id"].isin(stores["store_id"]).all()

Referential integrity means that every foreign key (a column that points to the primary key of another table) points to a row that exists. A line whose key points nowhere is an orphan record. Libraries such as pandera and Great Expectations turn checks like these into reusable data contracts, written agreements on the shape and rules of a table. The plain-pandas version below teaches the same ideas with no extra tools.

Examples 1 to 5 build one pipeline on data/sales_raw.csv. They share the variables raw (the file as loaded) and sales (the copy being cleaned), and they add one entry per step to a cleaning log. Examples 6 to 8 work on other datasets. Example 9 validates the result and prints the log.

Goal: Before you change anything, measure what is wrong with data/sales_raw.csv and compare each count with the data dictionary, which lists every problem that the export contains.

Step 1 — Load the file with default settings

Section titled “Step 1 — Load the file with default settings”
raw = pd.read_csv("data/sales_raw.csv")
print(raw.shape)
missing = raw.isna().sum()
print(missing[missing > 0])
Output
(1200, 13)
customer_id 18
region 14
channel 13
unit_price 8
discount 17
dtype: int64

The file has 1,200 lines and 13 columns. pandas found gaps in five columns. The data dictionary says that customer_id has 23 gaps, not 18, so some gaps are written as a token that pandas does not know.

Step 2 — Find the hidden missing-value tokens

Section titled “Step 2 — Find the hidden missing-value tokens”
for token in ["", "N/A", "-", "?", "unknown", "null"]:
hits = (raw == token).sum()
print(repr(token), hits[hits > 0].to_dict())
Output
'' {}
'N/A' {}
'-' {'customer_id': 5, 'region': 3, 'channel': 4, 'unit_price': 2, 'discount': 7}
'?' {}
'unknown' {}
'null' {}

raw == token compares every cell with the token and gives a table of True and False; .sum() counts the hits per column. Empty fields and N/A are already NaN, so they score 0 here. Only - survives as text. It is the token that the old system uses for “no value”.

Step 3 — Reload with explicit tokens and check the counts

Section titled “Step 3 — Reload with explicit tokens and check the counts”
NA_TOKENS = ["", "N/A", "-"]
raw = pd.read_csv("data/sales_raw.csv", keep_default_na=False, na_values=NA_TOKENS)
missing = raw.isna().sum()
expected = {
"customer_id": 23,
"region": 17,
"channel": 17,
"unit_price": 10,
"discount": 24,
}
found = missing[missing > 0].to_dict()
print(found)
assert found == expected
Output
{'customer_id': 23, 'region': 17, 'channel': 17, 'unit_price': 10, 'discount': 24}

keep_default_na=False with na_values makes the token list explicit: exactly the three tokens from data/config.json. Every count now equals the data dictionary. The assert turns that comparison into a check that runs every time.

allowed_regions = ["North", "South", "East", "West"]
region, product = raw["region"], raw["product"]
tidy_product = product.str.strip().str.replace(r"\s+", " ", regex=True)
problems = {
"exact duplicate rows": raw.duplicated().sum(),
"region not canonical": (region.notna() & ~region.isin(allowed_regions)).sum(),
"unit_price stored as text": raw["unit_price"].str.startswith("$").sum(),
"product with stray spaces": (product != tidy_product).sum(),
"quantity outside 1..50": (~raw["quantity"].between(1, 50)).sum(),
}
for name, count in problems.items():
print(f"{name:<28}{count:>5}")
print(raw[["unit_price", "discount", "quantity"]].dtypes)
Output
exact duplicate rows 36
region not canonical 259
unit_price stored as text 1190
product with stray spaces 95
quantity outside 1..50 10
unit_price str
discount float64
quantity int64
dtype: object

This problem inventory is the to-do list of the pipeline. Each number matches the data dictionary: 36 duplicates, 259 bad region spellings, 1,190 text prices, 95 product names with stray spaces and 10 impossible quantities. discount loads as float64 once - is a gap, but unit_price stays str because of the dollar signs.

Common mistakes:

  • Cleaning before you profile. Without the counts, you cannot tell whether a step fixed everything or nothing.
  • Trusting isna().sum() on the first load. Tokens that pandas does not know look like real text.
  • Using na_values=["-"] with the default list still on. It works here, but it also turns a real NA or None into a gap. State all tokens and switch the default list off.

Example 2 — Fix prices and normalize text

Section titled “Example 2 — Fix prices and normalize text”

Goal: Give unit_price a numeric dtype and rewrite region and product in their canonical forms. Count every change and log it.

Step 1 — Start the cleaning log and convert the prices

Section titled “Step 1 — Start the cleaning log and convert the prices”
log: list[dict] = []
def log_step(step: str, frame: pd.DataFrame, changed: int) -> None:
"""Record one step: its name, the rows left and the cells or rows changed."""
log.append({"step": step, "rows": len(frame), "changed": int(changed)})
sales = raw.copy()
price_text = sales["unit_price"]
n_dollar = price_text.str.startswith("$").sum()
n_comma = price_text.str.contains(",", regex=False).sum()
print("with $:", n_dollar, "| with comma:", n_comma)
digits = price_text.str.replace(r"[$,]", "", regex=True)
sales["unit_price"] = pd.to_numeric(digits, errors="coerce")
print("gaps:", price_text.isna().sum(), "->", sales["unit_price"].isna().sum())
print(sales["unit_price"].describe()[["min", "max"]].to_dict())
log_step("unit_price text to float", sales, price_text.notna().sum())
Output
with $: 1190 | with comma: 47
gaps: 10 -> 10
{'min': 14.99, 'max': 1299.0}

The gap count is 10 before and after the conversion, so every price that existed was converted. The minimum and maximum equal the cheapest and the most expensive product in data/products.csv (14.99 and 1,299.00), which is a quick range check. The log records 1,190 changed cells.

before = sales["region"]
sales["region"] = before.str.strip().str.title()
changed = (before != sales["region"]) & before.notna()
print("distinct before:", before.nunique(), "| after:", sales["region"].nunique())
print("cells changed:", changed.sum())
print(sales["region"].value_counts(dropna=False).to_dict())
log_step("region strip + title case", sales, changed.sum())
Output
distinct before: 20 | after: 4
cells changed: 259
{'South': 312, 'East': 304, 'North': 299, 'West': 268, nan: 17}

20 spellings collapse to 4. The change count needs & before.notna(): NaN != NaN is True, so without it every gap would count as a change. 259 cells changed, which matches the data dictionary.

before = sales["product"]
sales["product"] = before.str.strip().str.replace(r"\s+", " ", regex=True)
changed = before != sales["product"]
print("names changed:", changed.sum())
print(before[changed].head(3).map(repr).tolist())
products = pd.read_csv("data/products.csv")
print("unknown names:", (~sales["product"].isin(products["product"])).sum())
log_step("product strip + collapse spaces", sales, changed.sum())
Output
names changed: 95
["'Non-Slip Yoga Mat '", "' Adjustable Dumbbells'", "' Air Purifier'"]
unknown names: 0

\s+ matches one or more whitespace characters, so a double space becomes one space. map(repr) shows the quotes, which makes the stray spaces visible. After the fix, every name exists in data/products.csv: the reference table proves the cleaning is complete.

Step 4 — Check the category against the product

Section titled “Step 4 — Check the category against the product”
ref = products.set_index("product_id")
mismatch = sales["category"] != sales["product_id"].map(ref["category"])
print("category mismatches:", mismatch.sum())
print(sales[["unit_price", "discount", "region", "product"]].dtypes)
Output
category mismatches: 0
unit_price float64
discount float64
region str
product str
dtype: object

set_index("product_id") turns the product table into a lookup. map looks up the category of each line’s product. No line contradicts the reference table, so the category column needs no fix. Checking a column you do not need to change is still part of the job.

Common mistakes:

  • astype(float) on the price text. It raises ValueError: could not convert string to float: '$79.99'.
  • Replacing $ with str.replace("$", "", regex=True). In a regular expression, $ means “end of text”, so nothing is removed. Use regex=False or a character class [$].
  • Counting changes with before != after on a column with gaps. Every NaN counts as a change.

Example 3 — Parse three date formats safely

Section titled “Example 3 — Parse three date formats safely”

Goal: order_date mixes ISO dates, day-first dates and dates with month names. Parse all 1,200 values correctly and prove it with a second column.

dates = sales["order_date"]
patterns = {
"%Y-%m-%d": r"\d{4}-\d{2}-\d{2}",
"%d/%m/%Y": r"\d{2}/\d{2}/\d{4}",
"%B %d, %Y": r"[A-Z][a-z]+ \d{1,2}, \d{4}",
}
for fmt, pattern in patterns.items():
print(f"{fmt:<10} {dates.str.fullmatch(pattern).sum():>4}")
print(dates.iloc[6:9].tolist())
Output
%Y-%m-%d 723
%d/%m/%Y 276
%B %d, %Y 201
['2023-01-07', '07/01/2023', 'January 7, 2023']

str.fullmatch checks that the whole value matches a pattern. Counting the formats first tells you which parsers you need and how many values each one must parse. The three counts add up to 1,200, so no fourth format hides in the file. The counts match the data dictionary: 723, 276 and 201.

Step 2 — Try format=“mixed” and test the result

Section titled “Step 2 — Try format=“mixed” and test the result”
quick = pd.to_datetime(dates, format="mixed", dayfirst=True)
print("NaT:", quick.isna().sum(), "|", quick.min().date(), "to", quick.max().date())
print(dates.iloc[3], "->", quick.iloc[3].date())
by_order = quick.groupby(sales["order_id"]).min().sort_index()
print("dates rise with order_id:", by_order.is_monotonic_increasing)
Output
NaT: 0 | 2023-01-01 to 2024-12-31
2023-01-04 -> 2023-04-01
dates rise with order_id: False

Module 24 met this shortcut as a trap. Here you prove the damage with data. Every date parsed and all dates lie in 2023–2024, so the quick checks pass. The line 2023-01-04 shows the problem: dayfirst=True read it as 1 April. The data dictionary says that order_id increases with the date. is_monotonic_increasing checks that each value is greater than or equal to the one before. The test fails, so some dates are wrong.

parts = [pd.to_datetime(dates, format=fmt, errors="coerce") for fmt in patterns]
order_date = parts[0].combine_first(parts[1]).combine_first(parts[2])
print("NaT:", order_date.isna().sum())
by_order = order_date.groupby(sales["order_id"]).min().sort_index()
print("dates rise with order_id:", by_order.is_monotonic_increasing)
wrong = quick != order_date
all_iso = dates[wrong].str.fullmatch(patterns["%Y-%m-%d"]).all()
print("wrong in the quick parse:", wrong.sum(), "| all ISO:", all_iso)
Output
NaT: 0
dates rise with order_id: True
wrong in the quick parse: 269 | all ISO: True

The loop goes over the keys of patterns, which are the three format strings. Each format parses its own values. Now the dates rise with the order id. The quick parse had swapped day and month on 269 ISO dates, every one with a day of 12 or less.

Step 4 — Store the dates and log the step

Section titled “Step 4 — Store the dates and log the step”
sales["order_date"] = order_date
print(sales["order_date"].dtype)
print(sales["order_date"].dt.year.value_counts().sort_index().to_dict())
rewritten = dates != order_date.dt.strftime("%Y-%m-%d")
log_step("order_date 3 formats to datetime", sales, rewritten.sum())
Output
datetime64[us]
{2023: 508, 2024: 692}

The column is now datetime64. The changed count, 477, is the number of values that were not already ISO text (276 + 201).

Common mistakes:

  • Trusting format="mixed", dayfirst=True because it parses every value. A parse with no NaT can still be wrong. Test the dates against another column, such as an id that grows with time.
  • Calling pd.to_datetime(dates) with no format. pandas guesses one format from the first value and raises a ValueError at the first value in another format.
  • Using errors="coerce" and not counting the NaT values. Coercion hides every value it cannot read.

Example 4 — Remove duplicates and repair impossible quantities

Section titled “Example 4 — Remove duplicates and repair impossible quantities”

Goal: Remove the 36 duplicated lines, prove that the primary key is unique, and decide what to do with the 10 quantities outside the valid range of 1 to 50 units.

dup_all = sales.duplicated(keep=False)
print("rows in groups:", dup_all.sum(), "| extra copies:", sales.duplicated().sum())
first_key = sales.loc[sales.duplicated(), "order_id"].iloc[0]
print(sales.loc[sales["order_id"] == first_key, ["order_id", "product_id", "quantity"]])
Output
rows in groups: 72 | extra copies: 36
order_id product_id quantity
0 O000004 P002 1
29 O000004 P002 1

keep=False marks every member of a group: 72 rows form 36 pairs. The index labels 0 and 29 show that the copy sits 29 lines after the original. Looking at a few groups confirms that they are true copies before you delete anything.

Step 2 — Drop the exact duplicates and test the key

Section titled “Step 2 — Drop the exact duplicates and test the key”
rows_before = len(sales)
sales = sales.drop_duplicates()
key = ["order_id", "product_id"]
print(rows_before, "->", len(sales))
print("key duplicates left:", sales.duplicated(subset=key).sum())
log_step("drop exact duplicates", sales, rows_before - len(sales))
Output
1200 -> 1164
key duplicates left: 0

36 rows are gone and no key appears twice. The key test is the important one: if a duplicate differed in one column, such as a corrected discount, the exact test would miss it and the key test would find it.

Step 3 — Compare a range rule with the IQR rule

Section titled “Step 3 — Compare a range rule with the IQR rule”
qty = sales["quantity"]
q1, q3 = qty.quantile([0.25, 0.75])
lower, upper = q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1)
iqr_flag = (qty < lower) | (qty > upper)
range_flag = ~qty.between(1, 50)
print("IQR fences:", lower, upper, "| flagged:", iqr_flag.sum())
print("range 1..50 flagged:", range_flag.sum())
print(sorted(qty[range_flag].tolist()))
Output
IQR fences: -0.5 3.5 | flagged: 45
range 1..50 flagged: 10
[-3, -2, -2, -2, -1, -1, 250, 500, 999, 1000]

The quartiles of quantity are 1 and 2, so the IQR rule flags every line with 4 units or more, and the negatives: 45 lines, 35 of them real bulk orders. The business rule from data/config.json (min_quantity 1, max_quantity 50) flags only the 10 impossible values. For counts with a known valid range, a range rule beats a statistical rule.

Step 4 — Repair the quantities from revenue

Section titled “Step 4 — Repair the quantities from revenue”
implied = sales["revenue"] / (sales["unit_price"] * (1 - sales["discount"]))
whole = implied.round()
fix = range_flag & ((implied - whole).abs() < 0.01) & whole.between(1, 50)
print(pd.DataFrame({"quantity": qty, "implied": implied.round(4)})[range_flag])
sales["quantity_repaired"] = fix
sales.loc[fix, "quantity"] = whole[fix].astype("int64")
still_bad = ~sales["quantity"].between(1, 50)
print("repaired:", fix.sum(), "| still outside 1..50:", still_bad.sum())
log_step("repair quantity from revenue", sales, fix.sum())
Output
quantity implied
151 999 1.0
453 250 1.0
520 500 2.0
577 -3 1.0
684 -2 3.0
891 -2 1.0
893 -2 2.0
1008 -1 1.0
1081 -1 1.0
1107 1000 1.0
repaired: 10 | still outside 1..50: 0

The data dictionary says that revenue holds the correct value. So revenue ÷ (price × (1 − discount)) gives the true quantity. Revenue is rounded to cents, so the result is close to a whole number, not always equal to one; the tolerance of 0.01 units accepts that rounding error. All 10 implied quantities are whole numbers from 1 to 3, so the step repairs them. The flag column quantity_repaired keeps a record in the data itself. If an implied value were not a whole number, the row would keep its bad quantity and the validation step would catch it.

Common mistakes:

  • Dropping duplicates by key with keep="first" before you look at the groups. If the copies differ, you may keep the wrong version.
  • Using the IQR rule on small integer counts. With quartiles 1 and 2, normal bulk orders become “outliers”.
  • Taking the absolute value of a negative quantity. -3 might be a return of 3 units or a typo for 1; here the revenue says it was 1.

Example 5 — Fill the sales gaps from trusted sources

Section titled “Example 5 — Fill the sales gaps from trusted sources”

Goal: Fill the missing prices, regions and discounts from facts that the data already holds, label the missing channels and keep the lines with no customer.

gaps = sales.isna().sum()
print(gaps[gaps > 0].to_dict())
print("lines with any gap:", sales.isna().any(axis=1).sum(), "of", len(sales))
Output
{'customer_id': 23, 'region': 17, 'channel': 17, 'unit_price': 9, 'discount': 23}
lines with any gap: 87 of 1164

87 of the 1,164 lines have a gap. Dropping them would remove 7.5% of the lines and their revenue. Most of these gaps can be filled exactly, because each value is stored somewhere else too.

Step 2 — Fill prices and regions from the reference tables

Section titled “Step 2 — Fill prices and regions from the reference tables”
stores = pd.read_csv("data/stores.csv")
price_ref = sales["product_id"].map(products.set_index("product_id")["unit_price"])
region_ref = sales["store_id"].map(stores.set_index("store_id")["region"])
price_conflict = sales["unit_price"].notna() & (sales["unit_price"] != price_ref)
region_conflict = sales["region"].notna() & (sales["region"] != region_ref)
print("conflicts:", price_conflict.sum(), "prices,", region_conflict.sum(), "regions")
n_price, n_region = sales["unit_price"].isna().sum(), sales["region"].isna().sum()
sales["unit_price"] = sales["unit_price"].fillna(price_ref)
sales["region"] = sales["region"].fillna(region_ref)
log_step("fill unit_price from products", sales, n_price)
log_step("fill region from stores", sales, n_region)
print("filled:", n_price, "prices,", n_region, "regions")
Output
conflicts: 0 prices, 0 regions
filled: 9 prices, 17 regions

Before you trust a reference table, check that it agrees with the values you already have. No price and no region conflicts with the reference, so the filled values are facts, not estimates. The data dictionary confirms the rules: each line’s price equals the product’s price, and its region equals the store’s region.

Step 3 — Recover the discounts from revenue

Section titled “Step 3 — Recover the discounts from revenue”
implied = 1 - sales["revenue"] / (sales["unit_price"] * sales["quantity"])
to_fill = sales["discount"].isna()
print(implied[to_fill].round(2).value_counts().sort_index().to_dict())
sales["discount"] = sales["discount"].fillna(implied.round(2))
print("discounts allowed:", sales["discount"].isin([0, 0.05, 0.1, 0.2]).all())
log_step("fill discount from revenue", sales, to_fill.sum())
Output
{0.0: 14, 0.05: 4, 0.1: 3, 0.2: 2}
discounts allowed: True

The revenue formula has one unknown on each of these lines, so algebra gives the discount. Every recovered value is one of the four discounts the shop uses, which shows the method works. Rounding to 2 decimals removes tiny float errors such as 0.0500000001.

Step 4 — Label the channels and keep the unknown customers

Section titled “Step 4 — Label the channels and keep the unknown customers”
before_sum = sales.groupby("channel")["revenue"].sum().sum()
n_channel = sales["channel"].isna().sum()
sales["channel"] = sales["channel"].fillna("unknown")
print(sales.groupby("channel")["revenue"].sum().round(2).to_dict())
print("revenue that groupby hid before:", round(sales["revenue"].sum() - before_sum, 2))
log_step("label missing channel 'unknown'", sales, n_channel)
print("missing customer_id kept:", sales["customer_id"].isna().sum())
Output
{'online': 84083.29, 'store': 107844.33, 'unknown': 3734.88}
revenue that groupby hid before: 3734.88
missing customer_id kept: 23

No other column tells you whether a line was online or in a store, so the step writes an explicit label instead of a guess. This also matters for reports: groupby drops rows whose key is NaN, so the 17 lines with no channel vanished from every channel total. The customer_id gaps stay as NaN. The lines are still valid sales for revenue reports, and a fake id would create a customer who does not exist.

Common mistakes:

  • Filling a categorical gap with the most frequent value (store). That invents facts and inflates one group.
  • Filling from a reference table without checking for conflicts first. If the table is outdated, you overwrite nothing but you fill in wrong values.
  • Forgetting that groupby drops NaN keys. Pass dropna=False or label the gaps, as here.

Example 6 — Choose a fill for customer and house gaps

Section titled “Example 6 — Choose a fill for customer and house gaps”

Goal: Pick a defensible fill for total_charges in data/customers.csv and for lot_sqft in data/houses.csv, and measure the error and the bias of each choice.

customers = pd.read_csv("data/customers.csv")
gap = customers["total_charges"].isna()
print("gaps:", gap.sum(), "| tenure:", customers.loc[gap, "tenure_months"].unique())
print("mean fill would be:", round(customers["total_charges"].mean(), 2))
customers["total_charges"] = customers["total_charges"].fillna(0.0)
print("gaps left:", customers["total_charges"].isna().sum())
Output
gaps: 10 | tenure: [0]
mean fill would be: 1385.69
gaps left: 0

All 10 blank customers joined in December 2024 and have 0 months of tenure. They have not been billed yet, so their true total is 0. A mean fill would give each of them 1,385.69 USD of charges they never paid. Always look at the rows with gaps before you choose a statistic.

Step 2 — Count the cost of dropping rows

Section titled “Step 2 — Count the cost of dropping rows”
houses = pd.read_csv("data/houses.csv")
gaps = houses[["lot_sqft", "school_rating"]].isna()
print(gaps.sum().to_dict(), "| both:", gaps.all(axis=1).sum())
complete = houses.dropna(subset=["lot_sqft", "school_rating"])
print("rows kept:", len(complete), "of", len(houses))
has_gap = gaps.any(axis=1).to_numpy()
prices = houses["price"].to_numpy()
def median_gap(mask: np.ndarray) -> float:
return np.median(prices[mask]) - np.median(prices[~mask])
observed = median_gap(has_gap)
perm_rng = np.random.default_rng(42)
shuffled = np.array([median_gap(perm_rng.permutation(has_gap)) for _ in range(1000)])
print("median price difference:", observed)
print("share of shuffles as large:", (np.abs(shuffled) >= abs(observed)).mean())
Output
{'lot_sqft': 90, 'school_rating': 90} | both: 1
rows kept: 2821 of 3000
median price difference: 23500.0
share of shuffles as large: 0.233

The gaps sit in different rows (only 1 row has both), so dropna removes 179 houses, 6% of the data. The houses with gaps have a median price 23,500 USD above the others. Is that more than chance? The permutation check shuffles the gap mask 1,000 times: perm_rng.permutation puts the 179 gaps on random houses each time. In about a quarter of the shuffles, chance alone gives a difference at least as large. So the data shows no sign that the gaps depend on price, which is consistent with MCAR. Dropping is safe here but wasteful: it throws away 179 prices to lose 180 cells.

Step 3 — Compare fills on values you hide on purpose

Section titled “Step 3 — Compare fills on values you hide on purpose”
rng = np.random.default_rng(42)
known = houses.index[houses["lot_sqft"].notna()]
hidden = rng.choice(known, size=300, replace=False)
test = houses.copy()
test.loc[hidden, "lot_sqft"] = np.nan
lot = test["lot_sqft"]
area_median = test.groupby("neighborhood")["lot_sqft"].transform("median")
fills = {
"global mean": lot.fillna(lot.mean()),
"global median": lot.fillna(lot.median()),
"neighborhood median": lot.fillna(area_median),
}
truth = houses.loc[hidden, "lot_sqft"]
for name, filled in fills.items():
print(f"{name:<20} MAE {(filled[hidden] - truth).abs().mean():>6.0f} sq ft")
Output
global mean MAE 3662 sq ft
global median MAE 3627 sq ft
neighborhood median MAE 2432 sq ft

You cannot score a fill on real gaps, because the true values are unknown. So hide 300 known values, fill them and compare the fills with the truth. MAE (mean absolute error) is the average size of the error. The neighborhood median wins clearly: lot size depends on the area, and transform("median") gives each row the median of its own neighborhood.

Step 4 — Measure the shrinking spread and add an indicator

Section titled “Step 4 — Measure the shrinking spread and add an indicator”
lot = houses["lot_sqft"]
mean_filled = lot.fillna(lot.mean())
n, n_obs = len(lot), lot.notna().sum()
print("std:", round(lot.std(), 1), "| after mean fill:", round(mean_filled.std(), 1))
print("formula:", round(lot.std() * np.sqrt((n_obs - 1) / (n - 1)), 1))
houses["lot_sqft_missing"] = lot.isna()
area_median = houses.groupby("neighborhood")["lot_sqft"].transform("median")
houses["lot_sqft"] = lot.fillna(area_median)
print("flagged:", lot.isna().sum(), "| gaps left:", houses["lot_sqft"].isna().sum())
Output
std: 4901.1 | after mean fill: 4827.0
formula: 4827.0
flagged: 90 | gaps left: 0

The mean fill shrinks the standard deviation exactly as the formula predicts. The final choice is the neighborhood median plus a missing-value indicator, a True/False column that records which values were imputed. A model can then learn whether “missing” carries information, and an analyst can exclude imputed rows from a summary.

Common mistakes:

  • Filling with the mean by habit. Check the rows with gaps first: a structural gap needs a rule, not a statistic.
  • Scoring an imputation on the rows you filled. You have no truth there. Hide known values and score on them.
  • Computing the fill value on the whole dataset before a train/test split. That leaks test data into training.

Example 7 — Fill sensor gaps in a time series

Section titled “Example 7 — Fill sensor gaps in a time series”

Goal: data/sensors.csv holds readings from four sensors every 10 minutes, with 81 blank cells. Fill them so that each value fits its own sensor’s curve.

sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
value_cols = ["temperature_c", "humidity_pct", "vibration_mm_s"]
print(sensors[value_cols].isna().groupby(sensors["sensor_id"]).sum())
print(sensors[["timestamp", "sensor_id", "temperature_c"]].head(4))
Output
temperature_c humidity_pct vibration_mm_s
sensor_id
S1 6 11 10
S2 4 8 3
S3 6 5 10
S4 6 5 7
timestamp sensor_id temperature_c
0 2024-05-01 S1 20.21
1 2024-05-01 S2 22.30
2 2024-05-01 S3 19.40
3 2024-05-01 S4 24.52

The gaps are spread over all sensors and columns. The rows interleave the sensors: one row per sensor per timestamp. A fill that looks at the row above sees a different sensor.

Step 2 — Score four fills on hidden values

Section titled “Step 2 — Score four fills on hidden values”
col = "temperature_c"
known = sensors.index[sensors[col].notna()]
hidden = rng.choice(known, size=200, replace=False)
test = sensors.copy()
test.loc[hidden, col] = np.nan
by_sensor = test.groupby("sensor_id")[col]
fills = {
"sensor mean": test[col].fillna(by_sensor.transform("mean")),
"interpolate, no groups": test[col].interpolate(),
"ffill per sensor": by_sensor.ffill(),
"interpolate per sensor": by_sensor.transform(lambda s: s.interpolate()),
}
truth = sensors.loc[hidden, col]
for name, filled in fills.items():
print(f"{name:<24} MAE {(filled[hidden] - truth).abs().mean():.3f} °C")
Output
sensor mean MAE 1.780 °C
interpolate, no groups MAE 2.626 °C
ffill per sensor MAE 0.285 °C
interpolate per sensor MAE 0.230 °C

Interpolation estimates a missing value from its neighbors; interpolate() draws a straight line between the value before and the value after the gap. Forward fill (ffill) repeats the last known value. Per sensor, both follow the daily temperature cycle, and interpolation is the most accurate. Without groups, interpolation mixes neighboring sensors and is the worst of the four.

def fill_short_gaps(s: pd.Series, max_gap: int = 3) -> pd.Series:
"""Interpolate gaps of at most max_gap readings; leave longer gaps empty."""
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("limit=3: ", demo.interpolate(limit=3, limit_direction="both").tolist())
print("max_gap=3:", fill_short_gaps(demo).tolist())
filled = sensors.groupby("sensor_id")[value_cols].transform(fill_short_gaps)
print("gaps:", sensors[value_cols].isna().sum().sum(), "->", filled.isna().sum().sum())
for c in value_cols:
sensors[f"{c}_imputed"] = sensors[c].isna()
sensors[value_cols] = filled
print(sensors[[f"{c}_imputed" for c in value_cols]].sum().to_dict())
Output
limit=3: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, nan, 8.0, 9.0, 10.0, 11.0]
max_gap=3: [1.0, 2.0, 3.0, nan, nan, nan, nan, nan, nan, nan, 11.0]
gaps: 81 -> 0
{'temperature_c_imputed': 22, 'humidity_pct_imputed': 29, 'vibration_mm_s_imputed': 30}

The limit option of interpolate does not skip long gaps. In pandas 3.1, limit=3 fills the first 3 cells of a longer gap and leaves the rest; with limit_direction="both", it fills 3 cells from each end. The demo shows it: the 7-reading gap gets 6 invented values and keeps one empty cell in the middle. To leave long gaps fully empty, measure each gap. (~gap).cumsum() gives every gap cell the number of the last known value before it, so the gap cells of one run share a group, and transform("sum") counts them. mask then empties every filled cell whose run is longer than 3 readings (30 minutes). limit_direction="both" also fills a gap at the start or the end of a series by copying the nearest value. The longest real gap here is one reading, so every cell is filled, and three indicator columns remember which ones.

vib = sensors.groupby("sensor_id")["vibration_mm_s"]
before, after = vib.shift(1), vib.shift(-1)
lo, hi = np.minimum(before, after), np.maximum(before, after)
imputed = sensors["vibration_mm_s_imputed"]
inside = sensors["vibration_mm_s"].between(lo, hi)
print("imputed:", imputed.sum(), "| between their neighbors:", inside[imputed].sum())
print("max vibration:", sensors["vibration_mm_s"].max())
Output
imputed: 30 | between their neighbors: 29
max vibration: 18.98

shift(1) and shift(-1) give each reading its neighbors in the same sensor. 29 of the 30 imputed values lie between their neighbors, so the fill cannot create a new spike. The exception is the last S4 reading (2024-05-14 23:50). It has no next neighbor, so limit_direction="both" copied the previous value, 12.29; between is False because one limit is NaN. The fill touched only the blank cells, so the real spikes (up to 18.98 mm/s) are still there for anomaly detection in module 39. For irregular timestamps, use interpolate(method="time") on a DatetimeIndex, which weights by the real time gap.

Common mistakes:

  • Interpolating a long table with several series without groupby. The fill mixes sensors, stores or customers.
  • Filling long gaps with a straight line. limit alone does not prevent it; measure the gap length, as in fill_short_gaps, and report what stays empty.
  • Using fills that read the future in a forecast or a real-time detector. bfill, interpolation, limit_direction="both" or "backward", and centered rolling windows all use values after the gap. They are fine for cleaning history in a batch job. When a model must predict or alert at time t, use only ffill and trailing windows.

Example 8 — Compare IQR and z-score on house prices

Section titled “Example 8 — Compare IQR and z-score on house prices”

Goal: data/houses.csv contains 8 injected price errors, listed in the data dictionary. Test which outlier rule finds them without flagging hundreds of real houses.

Step 1 — Apply the IQR rule to the price

Section titled “Step 1 — Apply the IQR rule to the price”
import matplotlib.pyplot as plt
injected = ["H0537", "H0542", "H0751", "H0914", "H2277", "H0887", "H0957", "H1990"]
is_injected = houses["house_id"].isin(injected)
price = houses["price"]
q1, q3 = price.quantile([0.25, 0.75])
upper = q3 + 1.5 * (q3 - q1)
iqr_flag = (price < q1 - 1.5 * (q3 - q1)) | (price > upper)
print(f"Q1 {q1:,.0f} | Q3 {q3:,.0f} | upper fence {upper:,.0f}")
print("flagged:", iqr_flag.sum(), "| injected found:", (iqr_flag & is_injected).sum())
fig, ax = plt.subplots(figsize=(8, 3))
ax.hist(price / 1e6, bins=60, color="#4c78a8")
ax.axvline(upper / 1e6, color="#e45756", linestyle="--", label="IQR upper fence")
ax.set_xlabel("price (million USD)")
ax.set_ylabel("houses")
ax.legend()
plt.show()
Output
Q1 278,500 | Q3 560,375 | upper fence 983,188
flagged: 198 | injected found: 2
A right-skewed histogram of house prices with a long tail up to 3.7 million USD. The IQR upper fence at about 1 million USD cuts off the whole tail.
House prices with the IQR upper fence. Everything right of the dashed line is flagged.

Prices are right-skewed: most houses cost a few hundred thousand dollars, and a long tail of expensive homes stretches to the right. The IQR rule flags the whole tail, almost 200 houses, and finds only 2 of the 8 errors.

z = (price - price.mean()) / price.std()
z_flag = z.abs() > 3
print("flagged:", z_flag.sum(), "| injected found:", (z_flag & is_injected).sum())
print("lowest flagged price:", price[z_flag].min())
Output
flagged: 68 | injected found: 1
lowest flagged price: 1433500

The z-score flags fewer houses, but they are again the most expensive ones, and it finds only 1 error. The deflated errors (a Lakeview house sold at 252,500) sit in the middle of the overall distribution. No rule on the raw price can find them, because they are only strange for their neighborhood and size.

Step 3 — Add context: compare each house with its neighborhood’s price curve

Section titled “Step 3 — Add context: compare each house with its neighborhood’s price curve”
log_price, log_sqft = np.log(houses["price"]), np.log(houses["sqft"])
residual = pd.Series(np.nan, index=houses.index)
for rows in houses.groupby("neighborhood").groups.values():
slope, intercept = np.polyfit(log_sqft[rows], log_price[rows], deg=1)
residual[rows] = log_price[rows] - (intercept + slope * log_sqft[rows])
group = residual.groupby(houses["neighborhood"])
z_group = (residual - group.transform("mean")) / group.transform("std")
ctx_flag = z_group.abs() > 3
print("flagged:", ctx_flag.sum(), "| injected found:", (ctx_flag & is_injected).sum())
cols = ["house_id", "neighborhood", "sqft", "price"]
print(houses.loc[ctx_flag & ~is_injected, cols])
Output
flagged: 14 | injected found: 8
house_id neighborhood sqft price
159 H0160 Riverside 2030 294500
1167 H1168 Westfield 1690 144000
1584 H1585 Lakeview 2470 1814500
1715 H1716 Old Town 1160 621000
2173 H2174 Maple Grove 2730 303500
2593 H2594 Old Town 600 519000

Three changes give the rule context. The log makes the skewed prices roughly symmetric, which the z-score assumes. np.polyfit(x, y, deg=1) fits a straight line through the points (least squares; module 35 explains it), so each neighborhood gets its own line of log price against log size. The residual is the distance of a house from its neighborhood’s line. A simple price per square foot is not enough here: in this data, the price grows with size at a different rate in each neighborhood, so price per square foot still depends on size. Now 14 houses are flagged, and all 8 injected errors are among them. The other 6 are unusual but plausible: they are candidates for a human check, not for deletion.

houses["price_suspect"] = ctx_flag
low, high = price.quantile([0.01, 0.99])
capped = price.clip(low, high)
print("values capped:", (capped != price).sum())
print("mean price:", round(price.mean()), "| capped at 1%/99%:", round(capped.mean()))
print("mean without suspects:", round(price[~ctx_flag].mean()))
print(houses["price_suspect"].sum(), "houses flagged for review")
Output
values capped: 60
mean price: 476466 | capped at 1%/99%: 473196
mean without suspects: 475164
14 houses flagged for review

Capping with clip at the 1st and 99th percentiles pulls the 60 most extreme prices to the limits. It lowers the mean, but it also changes genuine expensive houses. Removing the suspects barely moves the mean, because they are few and on both sides. The pipeline keeps all rows and adds a price_suspect flag. Module 35 shows how a model trained on log prices reacts to such rows.

Common mistakes:

  • Running one global rule on skewed data and deleting what it flags. You delete the most valuable genuine records.
  • Treating “not flagged” as “correct”. The deflated errors pass every global test.
  • Capping before you know whether a value is an error. Capping changes real data, so log it like any other change.

Example 9 — Validate the clean table and print the cleaning log

Section titled “Example 9 — Validate the clean table and print the cleaning log”

Goal: Write a validate(df) -> list[str] function for the sales table, prove that it catches broken data, run it on the clean table and print the log of the whole pipeline.

customer_ids = set(customers["customer_id"])
REQUIRED = ["order_id", "order_date", "store_id", "product_id", "unit_price"]
KEY = ["order_id", "product_id"]
def validate(df: pd.DataFrame) -> list[str]:
"""Return one message per failed rule. An empty list means the table is valid."""
problems = []
for c in REQUIRED:
if df[c].isna().any():
problems.append(f"{c}: {df[c].isna().sum()} missing")
n_dup = df.duplicated(subset=KEY).sum()
if n_dup:
problems.append(f"key: {n_dup} duplicates")
bad_qty = ~df["quantity"].between(1, 50)
if bad_qty.any():
problems.append(f"quantity: {bad_qty.sum()} outside 1..50")
if not df["discount"].isin([0, 0.05, 0.1, 0.2]).all():
problems.append("discount: values outside {0, 0.05, 0.1, 0.2}")
if not df["order_date"].between("2023-01-01", "2024-12-31").all():
problems.append("order_date: outside 2023-2024")
if not df["region"].isin(["North", "South", "East", "West"]).all():
problems.append("region: unknown values")
expected = df["unit_price"] * df["quantity"] * (1 - df["discount"])
if not np.isclose(expected, df["revenue"], atol=0.01).all():
problems.append("revenue: does not match price x quantity x (1 - discount)")
refs = {"store_id": stores["store_id"], "product_id": products["product_id"]}
for c, ref in refs.items():
orphans = ~df[c].isin(ref)
if orphans.any():
problems.append(f"{c}: {orphans.sum()} orphan rows")
if not df["customer_id"].dropna().isin(customer_ids).all():
problems.append("customer_id: unknown customers")
return problems

Each rule appends a short message when it fails. The rules follow the checks table of the concepts section. The customer check skips the known gaps with dropna(), so it tests only the ids that exist.

broken = sales.copy()
broken.loc[broken.index[0], "quantity"] = -1
broken.loc[broken.index[1], "store_id"] = "S99"
broken = pd.concat([broken, broken.iloc[[2]]])
for message in validate(broken):
print(message)
Output
key: 1 duplicates
quantity: 1 outside 1..50
revenue: does not match price x quantity x (1 - discount)
store_id: 1 orphan rows

A check that never fails proves nothing. Breaking a copy in three known ways shows that the function finds each problem. The bad quantity also breaks the revenue rule, so one error can trigger several messages.

problems = validate(sales)
print(problems)
assert not problems, problems
print(sales.dtypes.astype(str).value_counts().to_dict())
Output
[]
{'str': 8, 'float64': 3, 'datetime64[us]': 1, 'int64': 1, 'bool': 1}

The empty list means that the clean table passes every rule. The assert would stop the pipeline with the list of messages if any rule failed. With it, the pipeline cannot write a clean file that breaks a rule.

Step 4 — Print the cleaning log and save the result

Section titled “Step 4 — Print the cleaning log and save the result”
from pathlib import Path
report = pd.DataFrame(log)
print(report.to_string(index=False))
Path("output").mkdir(exist_ok=True)
sales.to_csv("output/sales_clean.csv", index=False)
print("saved", len(sales), "rows and", sales.shape[1], "columns")
Output
step rows changed
unit_price text to float 1200 1190
region strip + title case 1200 259
product strip + collapse spaces 1200 95
order_date 3 formats to datetime 1200 477
drop exact duplicates 1164 36
repair quantity from revenue 1164 10
fill unit_price from products 1164 9
fill region from stores 1164 17
fill discount from revenue 1164 23
label missing channel 'unknown' 1164 17
saved 1164 rows and 14 columns

The log tells the story of the pipeline in ten lines: what each step did and how many rows were left. A reviewer can compare it with the data dictionary line by line. The clean file goes to output/, never back into data/. The project page turns these steps into one script that you can rerun on every export.

Common mistakes:

  • Validating with one assert per rule. The first failure hides the others; collect messages instead.
  • Writing checks only for problems you have already fixed. Add rules for what could go wrong next month, such as a new store id.
  • Never testing the validator. Break a copy on purpose and confirm that each rule fires.
Mistake Symptom Fix
A missing token such as - that pandas does not know A number column loads as str; isna().sum() is too low read_csv(..., keep_default_na=False, na_values=["", "N/A", "-"])
The default token list on real codes NA (North America) or None (a name) becomes NaN keep_default_na=False
df[col] == np.nan Always False df[col].isna()
before != after to count changes Every gap counts as a change (before != after) & before.notna()
pd.to_datetime(s, format="mixed", dayfirst=True) on a column with ISO dates ISO dates with day ≤ 12 swap day and month, silently One to_datetime per format, then combine_first
errors="coerce" and no count Bad values become gaps without a trace Count isna() before and after
str.replace("$", "", regex=True) Nothing is removed ($ is the end anchor) regex=False, or the class [$,]
Deduplicating before normalizing text North and north copies survive Normalize first, then drop_duplicates()
Only exact duplicate checks Rows with the same key but one changed value survive duplicated(subset=key)
Mean fill on structural gaps New customers get 1,385.69 USD of charges Look at the gap rows; use the rule (here 0)
interpolate() on interleaved series Values from one sensor fill another groupby(id)[col].transform(lambda s: s.interpolate())
IQR rule on small counts or skewed prices Hundreds of genuine values flagged Range rules for counts; log scale and groups for prices
z-score with huge errors in the data The errors hide themselves (masking) IQR or robust z-score (median and MAD)
groupby on a column with gaps Rows with NaN keys vanish from totals Label gaps or pass dropna=False
One assert per validation rule Only the first problem is reported Collect messages in a list; assert not problems, problems
  • Web development: a sign-up form normalizes e-mail addresses (strip, lower) and rejects duplicates by key before it writes to the database, the same steps as drop_duplicates(subset=...).
  • Data engineering: nightly ETL jobs run validation checks like validate() and stop the load when a rule fails, so that dashboards never show half-broken data. Tools such as dbt tests and Great Expectations formalize this.
  • Automation and finance: an accounting script that imports bank exports must parse 07/01/2023 as the bank meant it and strip $ and thousands separators from amounts.
  • Monitoring: operations teams fill short gaps in metrics by interpolation and flag spikes with robust z-scores before they page an engineer.
  • Profile before you clean. Count every problem and compare the counts with documentation; turn each comparison into an assert.
  • Declare missing-value tokens explicitly with keep_default_na=False and na_values. NaN never equals anything; test with isna().
  • Ask why a value is missing (MCAR, MAR, MNAR, structural). Dropping rows biases the data unless the gaps are MCAR.
  • Prefer exact facts over estimates: reference tables and formulas fill many gaps exactly. When you must estimate, choose a group-wise median or a per-series interpolation, score it on hidden known values and add an indicator column.
  • Mean imputation shrinks the variance by the factor (nobs−1)/(n−1)(n_\text{obs} - 1)/(n - 1) and weakens correlations.
  • Remove exact duplicates, then check the primary key with duplicated(subset=key).
  • Convert types with the pattern: strip junk, coerce, count new gaps. Normalize text to one canonical form and check it against the allowed values.
  • Parse mixed date formats one format at a time. format="mixed" with dayfirst=True silently swaps ISO dates in pandas 3.
  • The IQR rule resists masking; the z-score does not. Both flag genuine extremes on skewed data. Add context (log scale, groups) and prefer flags to deletion.
  • End the pipeline with a validate(df) -> list[str] function and a cleaning log that counts what each step changed.

Q1. read_csv reports 18 missing customer ids, but the documentation says 23. What is the most likely cause, and how do you fix it?

Answer

Some gaps use a token that pandas does not treat as missing, such as -. Count candidate tokens with (raw == "-").sum(), then reload with keep_default_na=False, na_values=["", "N/A", "-"].

Q2. Why does (before != after).sum() overcount the changes on a column with gaps?

Answer

NaN != NaN is True, so every gap that stayed a gap counts as a change. Use ((before != after) & before.notna()).sum().

Q3. A column holds 2023-01-07 and 07/01/2023, both meaning 7 January. What does pd.to_datetime(s, format="mixed", dayfirst=True) give in pandas 3, and what should you use instead?

Answer

It gives 2023-07-01 for the ISO value and 2023-01-07 for the day-first value: the ISO date is swapped. Parse each format with its own format= and errors="coerce", then combine with combine_first.

Q4. What is the difference between MCAR and MNAR? Give an example of each.

Answer

MCAR gaps are unrelated to any value, such as cells lost at random in a transfer. MNAR gaps depend on the missing value itself, such as high earners who skip the income question. Dropping MCAR rows only loses data; dropping MNAR rows biases the result.

Q5. You fill 3% of a column with its mean. What happens to the mean, the standard deviation and the correlation with other columns?

Answer

The mean stays the same. The variance shrinks by the factor (nobs−1)/(n−1)(n_\text{obs} - 1)/(n - 1), about 3%, so the standard deviation shrinks by about 1.5%. Correlations with other columns move toward 0, because the filled values do not vary with them.

Q6. When is drop_duplicates() not enough, and what do you add?

Answer

When two rows describe the same event but differ in one column, for example a corrected discount or North versus north. Normalize the text first, then check the primary key with df.duplicated(subset=["order_id", "product_id"], keep=False) and decide which copy to keep.

Q7. Why can the z-score rule miss several large quantity errors in a column of 200 small counts, while the IQR rule finds them? And why can |z| > 3 never fire on a column of 10 values?

Answer

The errors inflate the mean and the standard deviation, so their z-scores stay small and they hide each other (masking). The IQR rule uses quartiles, which a few extreme values cannot move. With the sample standard deviation, no value among nn can have ∣z∣|z| above (n−1)/n(n-1)/\sqrt{n}, which is 2.85 for n=10n = 10.

Q8. Why should you interpolate sensor readings with groupby("sensor_id") in a table that interleaves four sensors?

Answer

Without groups, interpolate() uses the rows above and below, which belong to other sensors. Grouping makes each sensor’s gaps use only that sensor’s neighbors.

Q9. A validation function returns a list of messages instead of raising at the first problem. Why is that better in a pipeline?

Answer

You see every problem in one run, so you can fix them together. The pipeline still stops with one assert not problems, problems, which prints the whole list.

Q10. What is referential integrity, and how do you check it in pandas?

Answer

Every foreign key points to an existing row of the other table, such as each store_id in the sales data existing in stores.csv. Check it with ~df["store_id"].isin(stores["store_id"]) (orphans are True), or with merge(..., how="left", indicator=True) and count the left_only rows.

Q11. The IQR rule flags 198 houses by price. Should you delete them?

Answer

No. House prices are right-skewed, so the rule flags the genuine expensive tail. Add context (log price per square foot within each neighborhood), flag the few remaining suspects in a column and let a person check them.

Your progress

0 / 4 done

  • Exercises: 27 exercises with hints and full solutions, from missing-value tokens to a full validation suite.
  • Mini-project: turn the sales cleaning steps into one repeatable script with a cleaning report.
  • Cheat sheet: every cleaning method of this module, with its pandas call and its trade-off.
  • Next module: 27. Exploratory data analysis explores the clean data: distributions, relationships and a written list of findings.