Sub topic 5
Validating data: schema, ranges, and missing values
This chapter assumes you can write pytest tests, read a pandas DataFrame, and run a GitHub Actions workflow. Earlier chapters covered the layered test strategy and unit tests for feature code. Here the subject is the data itself: a check that fails the build when a dataset is not the one your model expects.
Why data needs its own tests
A unit test proves that code does what you wrote. It says nothing about the file the code reads. A column can be renamed upstream, a unit can change from dollars to cents, or a join can start producing nulls. The training job still runs and the model still trains, but the model is worse, and nothing raises an error.
Data validation turns these silent failures into loud ones. You write down what "valid" means for your training data and check every dataset against that definition. Three kinds of rule cover most problems:
- Schema rules say which columns exist and what type each has.
- Range rules say which values are allowed in each column.
- Completeness rules say how many missing values you tolerate.
Where validation runs in CI
You can run validation at two points, and they answer different questions.
- On a small committed sample. The sample is a few hundred rows under
tests/data/. It runs on every pull request. A failure means a code or schema change broke the contract, or the sample went stale. - On the real dataset. The job runs just before training, in a scheduled or retraining job. A failure means the incoming data changed.
This chapter focuses on the first point. The same function works for both, which is the main reason to write validation as a plain function.
A validation function that returns errors
The design choice that matters most is that the validator returns a list of problems and does not raise on the first one. A list lets CI print every problem in one run, so you fix the data once instead of five times. It also makes the function easy to test, because you compare the list to an expected value.
import pandas as pd
EXPECTED_DTYPES = {"age": "int64", "income": "float64", "label": "int64"}
def validate_training_data(df: pd.DataFrame, max_missing: float = 0.05) -> list[str]:
errors = []
for col, dtype in EXPECTED_DTYPES.items():
if col not in df.columns:
errors.append(f"missing column: {col}")
elif str(df[col].dtype) != dtype:
errors.append(f"{col}: expected {dtype}, got {df[col].dtype}")
if "age" in df.columns and not df["age"].between(0, 120).all():
errors.append("age outside [0, 120]")
if "label" in df.columns and not df["label"].isin([0, 1]).all():
errors.append("label contains values other than 0 and 1")
if len(df) > 0 and df.isna().mean().max() > max_missing:
errors.append(f"missing-value fraction above {max_missing}")
return errors
def test_sample_data_is_valid():
df = pd.read_csv("tests/data/sample.csv")
assert validate_training_data(df) == []Each block of the function maps to one kind of rule.
Schema checks
The loop over EXPECTED_DTYPES reports two different failures. A column that is absent is reported as missing column. A column that exists with the wrong dtype is reported with both the expected and the actual type. The elif matters: without it, a missing column would raise a KeyError when the code reads df[col].dtype.
The function does not reject extra columns. That is deliberate. Adding a column upstream is usually harmless, while removing or retyping one usually breaks training. If your feature code selects columns by position or by df.columns, add a check that the column set is exactly what you expect.
Range checks
between(0, 120) is inclusive on both ends. It returns a boolean Series, and .all() collapses it to one decision. The label check uses isin([0, 1]) because the rule is a set of allowed values, not an interval.
Choose range bounds from domain knowledge, not from the sample. If you set the age limit to the sample's maximum, the test fails the first time a real customer is older. A bound should mark values that cannot be true, such as an age of 400 or a negative income, and not values that are merely unusual.
Missing-value checks
df.isna().mean() gives the fraction of missing values per column. Taking .max() finds the worst column. The check passes only if every column is under the threshold. The len(df) > 0 guard avoids a division by zero warning and a NaN comparison on an empty frame. An empty frame should fail somewhere, though, so also assert a minimum row count if empty data is possible in your pipeline.
A single global threshold is a blunt tool. If income is allowed to be 20% missing but age must be complete, use a dict of per-column limits instead.
Testing the validator itself
A validator that never fails is worse than none, because it gives false confidence. The committed-sample test only proves that good data passes. You also need tests that show bad data is caught. Build a small valid frame, break one thing at a time, and assert the exact error.
Save the function above as validation.py, then add this test file.
import pandas as pd
from validation import validate_training_data
def make_valid(n: int = 100) -> pd.DataFrame:
return pd.DataFrame(
{
"age": [30] * n,
"income": [50_000.0] * n,
"label": [0, 1] * (n // 2),
}
)
def test_valid_frame_has_no_errors():
assert validate_training_data(make_valid()) == []
def test_missing_column_is_reported():
df = make_valid().drop(columns=["income"])
assert "missing column: income" in validate_training_data(df)
def test_age_out_of_range_is_reported():
df = make_valid()
df.loc[0, "age"] = 150
assert validate_training_data(df) == ["age outside [0, 120]"]
def test_bad_label_is_reported():
df = make_valid()
df.loc[0, "label"] = 2
assert validate_training_data(df) == [
"label contains values other than 0 and 1"
]
def test_too_many_missing_values_is_reported():
df = make_valid()
df.loc[:9, "income"] = None # 10% missing
assert validate_training_data(df) == ["missing-value fraction above 0.05"]
def test_one_missing_age_is_caught_twice():
df = make_valid()
df["age"] = df["age"].astype("float64")
df.loc[0, "age"] = float("nan")
errors = validate_training_data(df)
assert "age: expected int64, got float64" in errors
assert "age outside [0, 120]" in errorsThe last test documents a behavior that surprises many people, covered next.
Gotchas
Missing values change dtypes
An integer column in pandas cannot hold NaN. As soon as a single value is missing, pandas stores the column as float64. That is why test_one_missing_age_is_caught_twice reports a dtype error as well as a range error. The schema check is therefore also a missing-value check for integer columns, even when the missing fraction is far below the threshold.
If you want to allow a few missing integers, use pandas' nullable Int64 dtype and put "Int64" in EXPECTED_DTYPES. Decide this on purpose. Do not loosen the check just to make a test pass.
Comparisons with NaN are false
between and isin return False for NaN. A single missing age therefore fails the range check, even though no out-of-range value is present. If missing values are acceptable in a column, drop them before the range check: df["age"].dropna().between(0, 120).all(). Then the completeness rule is the only one that judges missingness.
CSV round trips lose types
pd.read_csv infers dtypes from the values. A column that is all whole numbers becomes int64, even if your pipeline treats it as a float. A column with one stray string becomes object. Both cause schema failures. Both are useful signals, but the cause is often the file format and not the data. If dtypes matter, pass dtype= to read_csv, or store the sample as Parquet, which keeps types.
A stale sample hides problems
The committed sample passes by construction. If the real data drifts away from it, the pull-request check stays green while the production check fails. Refresh the sample when the schema changes. Keep the full-data validation in the training job so the real dataset is checked against the same function.
Choosing a library
You can write validators by hand, as above, or use a library. Pandera expresses the same rules as a declarative schema. Great Expectations adds reporting and a larger set of built-in checks.
| Approach | Strengths | Costs |
|---|---|---|
| Hand-written function | No dependency, easy to read, fits one dataset | You maintain every rule and message |
| Declarative schema library | Rules read like a spec, rich built-in checks | New dependency and API to learn |
| Full data-quality platform | Reports, history, many data sources | Heavier setup, more to operate |
For a project with a handful of columns, the hand-written function is a reasonable start. Move to a library when the number of rules, or the number of datasets, makes the function hard to review.
Checklist for a data validation test
- The validator returns a list of problems, not a single boolean or an exception.
- Each rule has a test with data that breaks only that rule.
- Range bounds come from the domain, not from the sample.
- Missing-value limits are chosen per column where the columns differ.
- The sample file is small, committed, and refreshed when the schema changes.
- The same function runs on the full dataset before training.
Exercise
A teammate changes the data export so that income is sometimes missing for 2% of rows, and age is occasionally missing for one row in 1,000. The validator above still fails on the committed sample. What are the two reasons the age column fails, and how would you change the validator so that a tiny number of missing ages is allowed while out-of-range ages are still rejected?
Show answer
A missing age turns the int64 column into float64, so the dtype check fails. The NaN value also makes between(0, 120) return False, so the range check fails. The missing fraction is far below 0.05, so that check passes. To allow a few missing ages, set the expected dtype for age to the nullable "Int64" (and cast the column on load), and run the range check on df["age"].dropna(). The completeness rule, ideally with a per-column limit for age, then decides how many missing ages are acceptable.
Exercise
Write a pytest test that checks the validator reports "missing column: label" when the label column is absent, and explain why the validator's elif between the missing-column check and the dtype check is needed.
Show answer
The test is df = make_valid().drop(columns=["label"]) followed by assert "missing column: label" in validate_training_data(df). The elif is needed because the dtype branch reads df[col].dtype. If the column were absent and the code used a plain if, that line would raise a KeyError and the function would crash instead of returning a readable list of errors.