Turn assumptions about your data into executable Pandera schemas, validate at pipeline boundaries with pandas and Polars, quarantine bad rows, and version schemas as data contracts with CI tests.
Most data bugs do not raise exceptions. A column arrives as text instead of numbers, a country code changes case, an upstream team starts sending amounts in cents, and your pipeline keeps running and produces confident, wrong numbers. This tutorial shows how to turn your assumptions about data into executable schemas with Pandera, how to validate at the boundaries of a pipeline, how to quarantine bad rows instead of crashing, and how to treat a schema as a versioned contract between the team that produces data and the teams that consume it.
The examples were run on Python 3.13 with pandera 0.36.0, pandas 3.1.2, polars 2.2.0, numpy 2.5.5 and pytest 9.2.0. Every output shown below comes from those runs; long outputs are shortened with "...".
Python code fails loudly when types are wrong: call a method that does not exist and you get an exception. Dataframe code is different. Most operations are defined for every dtype, missing values propagate instead of raising, and aggregations happily skip what they cannot handle. Consider a small orders extract where one amount uses a thousands separator and one country code is lower case:
import pandas as pd
orders = pd.DataFrame({
"order_id": [1, 2, 3, 4],
"amount": ["19.99", "5.00", "1,250.00", "12.50"],
"country": ["NL", "DE", "nl", "BE"],
})
orders["amount"] = pd.to_numeric(orders["amount"], errors="coerce")
print(orders)
print(orders.groupby("country")["amount"].sum())
order_id amount country
0 1 19.99 NL
1 2 5.00 DE
2 3 NaN nl
3 4 12.50 BE
country
BE 12.50
DE 5.00
NL 19.99
nl 0.00
Name: amount, dtype: float64
Nothing raised. The largest order in the batch silently became NaN, then 0.00 after the group sum, and the Dutch revenue is split across two keys. A dashboard built on this would be wrong, and nobody would know until someone compared it with the bank statement.
The fix is not more defensive code in every transformation, but stating your assumptions once, in a form a machine can check, at the places where data crosses a boundary.
Pandera lets you describe a dataframe as a class. Each annotated attribute is a column with a dtype; pa.Field adds built-in checks; decorated methods add custom checks. In current releases the pandas integration lives in pandera.pandas, and the Polars integration in pandera.polars. Importing the top-level pandera module for pandas still works but emits a FutureWarning announcing its removal, so use the explicit module.
# schemas.py
import pandera.pandas as pa
from pandera.typing import Series
class Orders(pa.DataFrameModel):
order_id: Series[int] = pa.Field(unique=True, gt=0)
customer_id: Series[int] = pa.Field(gt=0)
amount: Series[float] = pa.Field(ge=0, le=100_000)
currency: Series[str] = pa.Field(isin=["EUR", "USD", "GBP"])
country: Series[str] = pa.Field(str_matches=r"^[A-Z]{2}$")
discount: Series[float] = pa.Field(ge=0, le=1, nullable=True)
created_at: Series[pa.DateTime]
class Config:
strict = True
coerce = True
@pa.check("amount")
def amount_has_cents_precision(cls, s: Series[float]) -> Series[bool]:
return (s * 100).round(6) % 1 == 0
@pa.dataframe_check
def discount_only_on_positive_amounts(cls, df) -> Series[bool]:
return df["discount"].isna() | (df["amount"] > 0)
A few design choices are worth spelling out:
amount is an error unless you opt in with nullable=True, as done for discount. This default is the single most useful property of the library: it forces you to decide, per column, whether "missing" is a legitimate state.strict = True rejects columns that are not in the schema. Use it at ingest, where an unexpected column usually means the producer changed something. Use strict = "filter" if you want to drop unknown columns silently instead.coerce = True converts each column to its declared dtype before checks run. Raw CSV and JSON data arrives as strings; coercion turns "19.99" into a float and "2026-11-01" into a timestamp. If a value cannot be converted, that is reported as a failure rather than turned into NaN.@pa.check) receive a Series and return a boolean Series, one result per row. Dataframe checks (@pa.dataframe_check) receive the whole frame, which is what you need for rules that relate several columns ("wide" checks).import pandas as pd
from schemas import Orders
raw = pd.DataFrame({
"order_id": ["1", "2", "3"],
"customer_id": [10, 11, 10],
"amount": ["19.99", "5", "0"],
"currency": ["EUR", "EUR", "USD"],
"country": ["NL", "DE", "BE"],
"discount": [0.1, None, None],
"created_at": ["2026-11-01", "2026-11-02", "2026-11-03"],
})
orders = Orders.validate(raw)
print(orders.dtypes.to_string())
order_id int64
customer_id int64
amount float64
currency str
country str
discount float64
created_at datetime64[ns]
validate returns a new, coerced dataframe. Always continue with the return value, not with the input: the input still contains strings.
By default, validation stops at the first failure and raises SchemaError. That is fine in a unit test, but in a pipeline you want the full picture in one run. Pass lazy=True to collect every failure and raise a single SchemaErrors (plural) at the end:
import pandas as pd
import pandera.pandas as pa
from schemas import Orders
raw = pd.DataFrame({
"order_id": ["1", "2", "1"],
"customer_id": [10, 11, 10],
"amount": ["19.99", "5", "-3.5"],
"currency": ["EUR", "eur", "USD"],
"country": ["NL", "DE", "BE"],
"discount": [0.5, None, 0.2],
"created_at": ["2026-11-01", "2026-11-02", "2026-11-03"],
"source": "web",
})
try:
Orders.validate(raw, lazy=True)
except pa.errors.SchemaErrors as exc:
report = exc.failure_cases.drop_duplicates(["check", "index"])
print(report[["column", "check", "failure_case", "index"]].to_string(index=False))
column check failure_case index
order_id discount_only_on_positive_amounts 1 2
Orders column_in_schema source None
order_id field_uniqueness 1 0
order_id field_uniqueness 1 2
amount greater_than_or_equal_to(0) -3.5 2
currency isin(['EUR', 'USD', 'GBP']) eur 1
exc.failure_cases is a regular dataframe with one row per failing value: the column, the check that failed, the offending value and the row index. That makes it easy to log, count, store or turn into a ticket. Two details matter when you process it:
("check", "index"); the column shown for the wide check is simply the first one.None). They describe the dataset, not a row, and should usually stop the pipeline.str(exc) renders the same information as a JSON summary grouped into SCHEMA and DATA errors, which suits log aggregation.
Validating every intermediate dataframe is expensive and noisy. Validate where responsibility changes hands instead. In a typical analytics or machine learning pipeline there are three such points:
The @pa.check_types decorator validates function arguments and return values that are annotated with DataFrame[Model]. It turns a function signature into a boundary:
import numpy as np
import pandas as pd
import pandera.pandas as pa
from pandera.typing import DataFrame, Series
from schemas import Orders
class CustomerFeatures(pa.DataFrameModel):
customer_id: Series[int] = pa.Field(unique=True)
n_orders: Series[int] = pa.Field(ge=1)
total_amount: Series[float] = pa.Field(ge=0)
share_discounted: Series[float] = pa.Field(in_range={"min_value": 0, "max_value": 1})
class Config:
strict = True
@pa.dataframe_check(error="fewer than 50 customers: refusing to train")
def enough_rows(cls, df) -> bool:
return len(df) >= 50
@pa.dataframe_check(error="median basket outside expected band")
def median_basket_plausible(cls, df) -> bool:
median = (df["total_amount"] / df["n_orders"]).median()
return 10 <= median <= 500
@pa.check_types(lazy=True)
def build_features(orders: DataFrame[Orders]) -> DataFrame[CustomerFeatures]:
g = orders.groupby("customer_id")
return pd.DataFrame({
"n_orders": g.size(),
"total_amount": g["amount"].sum(),
"share_discounted": g["discount"].apply(lambda s: s.notna().mean()),
}).reset_index()
Now feed it synthetic orders, and then the same orders with amounts multiplied by 100, the kind of unit change that happens when a producer switches from euros to cents:
rng = np.random.default_rng(7)
n = 500
orders = pd.DataFrame({
"order_id": np.arange(1, n + 1),
"customer_id": rng.integers(1, 120, n),
"amount": rng.gamma(2.0, 40.0, n).round(2),
"currency": "EUR",
"country": "NL",
"discount": np.where(rng.random(n) < 0.2, 0.1, np.nan),
"created_at": pd.Timestamp("2026-11-01"),
})
features = build_features(orders)
print(features.shape)
try:
build_features(orders.assign(amount=orders["amount"] * 100))
except pa.errors.SchemaErrors as exc:
print(exc.failure_cases[["check", "failure_case"]].to_string())
(118, 4)
check failure_case
0 median basket outside expected band False
The two dataframe checks of CustomerFeatures return a single boolean instead of one value per row: they describe the dataset as a whole. Every individual amount in the second call is still non-negative, below the upper bound and has cent precision, so the input schema passes. Only the dataset-level check on the output notices that the median basket jumped by two orders of magnitude. Row-level rules guard formats; distribution rules guard meaning. You need both.
Derive the bounds from historical data and keep them wide: a check that fires every week without a real problem gets disabled.
Failing the whole batch because seven rows out of a million have a lower-case currency code is often the wrong trade-off. The alternative is to split the batch: valid rows continue, invalid rows go to a quarantine table with the reason attached, and someone reviews them. Pandera supports this pattern directly through the failure case report.
import numpy as np
import pandas as pd
import pandera.pandas as pa
from schemas import Orders
def split_valid(df: pd.DataFrame, schema=Orders) -> tuple[pd.DataFrame, pd.DataFrame]:
try:
return schema.validate(df, lazy=True), df.iloc[0:0]
except pa.errors.SchemaErrors as exc:
fc = exc.failure_cases
# schema-level problems (missing columns, wrong dtypes) have no row index:
# those are not row defects, so let them crash the pipeline.
if fc["index"].isna().any():
raise
bad_idx = fc["index"].astype(int).unique()
reasons = (fc.groupby("index")["check"]
.agg(lambda s: "; ".join(sorted(set(map(str, s))))))
quarantined = df.loc[bad_idx].assign(_reason=reasons)
valid = schema.validate(df.drop(index=bad_idx))
return valid, quarantined
Run it on 1,000 synthetic orders with a few realistic defects injected:
rng = np.random.default_rng(42)
n = 1_000
raw = pd.DataFrame({
"order_id": np.arange(1, n + 1),
"customer_id": rng.integers(1, 200, n),
"amount": rng.gamma(2.0, 40.0, n).round(2),
"currency": rng.choice(["EUR", "USD", "GBP"], n),
"country": rng.choice(["NL", "DE", "BE", "FR"], n),
"discount": np.where(rng.random(n) < 0.2, 0.1, np.nan),
"created_at": pd.date_range("2026-01-01", periods=n, freq="h"),
})
raw.loc[rng.choice(n, 7, replace=False), "currency"] = "eur"
raw.loc[rng.choice(n, 3, replace=False), "amount"] = -1.0
raw.loc[rng.choice(n, 2, replace=False), "country"] = "Netherlands"
valid, quarantined = split_valid(raw)
print(len(valid), "valid,", len(quarantined), "quarantined")
print(quarantined[["order_id", "amount", "currency", "country", "_reason"]].head(5).to_string())
988 valid, 12 quarantined
order_id amount currency country _reason
662 663 -1.00 GBP FR greater_than_or_equal_to(0)
676 677 -1.00 USD BE greater_than_or_equal_to(0)
790 791 -1.00 GBP FR greater_than_or_equal_to(0)
190 191 18.60 eur FR isin(['EUR', 'USD', 'GBP'])
306 307 97.26 eur DE isin(['EUR', 'USD', 'GBP'])
Three rules make quarantine safe in practice:
len(quarantined) / len(df) with a limit and fail above it.schema.validate call is cheap insurance: dataframe-level checks such as uniqueness can behave differently after rows are removed, and you want the coerced output anyway.For the simple case where you only want to drop invalid rows and do not need the quarantine table, Pandera has a built-in option. With drop_invalid_rows = True in the model's Config and lazy=True, failing rows are removed from the output instead of raising:
import pandas as pd
import pandera.pandas as pa
from pandera.typing import Series
class Readings(pa.DataFrameModel):
sensor: Series[str]
value: Series[float] = pa.Field(in_range={"min_value": -40, "max_value": 125})
class Config:
drop_invalid_rows = True
df = pd.DataFrame({"sensor": ["a", "b", "c"], "value": [21.5, 999.0, -3.0]})
print(Readings.validate(df, lazy=True))
sensor value
0 a 21.5
2 c -3.0
Use this with care: rows disappear without a trace. In anything that feeds money, compliance or model training, prefer the explicit quarantine so the dropped rows are counted and reviewable.
The Polars integration uses the same concepts with Polars-native types. Annotations are plain Python types (or Polars dtypes), and custom checks receive a PolarsData object and return a lazy frame of booleans, so they compose with Polars' query optimiser:
import polars as pl
import pandera.polars as pa
class OrdersPl(pa.DataFrameModel):
order_id: int = pa.Field(unique=True, gt=0)
amount: float = pa.Field(ge=0)
currency: str = pa.Field(isin=["EUR", "USD", "GBP"])
discount: float = pa.Field(nullable=True, in_range={"min_value": 0, "max_value": 1})
class Config:
strict = True
coerce = True
@pa.check("currency")
def upper_case(cls, data: pa.PolarsData) -> pl.LazyFrame:
return data.lazyframe.select(
pl.col(data.key) == pl.col(data.key).str.to_uppercase()
)
df = pl.DataFrame({
"order_id": [1, 2, 3],
"amount": ["19.99", "-5", "7.5"],
"currency": ["EUR", "eur", "USD"],
"discount": [None, 0.1, 1.5],
})
try:
OrdersPl.validate(df, lazy=True)
except pa.errors.SchemaErrors as exc:
print(exc.failure_cases.select("column", "check", "failure_case", "index"))
shape: (4, 4)
┌──────────┬─────────────────────────────┬──────────────┬───────┐
│ column ┆ check ┆ failure_case ┆ index │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i32 │
╞══════════╪═════════════════════════════╪══════════════╪═══════╡
│ amount ┆ greater_than_or_equal_to(0) ┆ -5.0 ┆ 1 │
│ currency ┆ isin(['EUR', 'USD', 'GBP']) ┆ eur ┆ 1 │
│ currency ┆ upper_case ┆ eur ┆ 1 │
│ discount ┆ in_range(0, 1) ┆ 1.5 ┆ 2 │
└──────────┴─────────────────────────────┴──────────────┴───────┘
There is one behaviour you must know about. When you validate a pl.LazyFrame, Pandera by default checks only schema-level properties (column names and dtypes), because data checks would force the query to execute. In our run, OrdersPl.validate(df.lazy()) returned a LazyFrame without complaint, even though the data contains a negative amount; calling .collect() and validating the resulting DataFrame raised immediately.
You have two options. Validate a collected DataFrame at the boundary, which is usually what you want at ingest. Or set the environment variable PANDERA_VALIDATION_DEPTH=SCHEMA_AND_DATA, which makes Pandera run data checks on lazy frames as well; we confirmed that with this variable set, the same lazy validation raised on the negative amount. Be explicit about which one you rely on, because a pipeline that "validates" lazy frames without data checks gives a false sense of safety.
A schema in your own repository protects you. A data contract is the same schema, owned by the producing team, published so that consumers can rely on it, and changed under rules both sides agree on. Pandera models are a practical format for this: they are code, they can be packaged and imported, and they are executable on both sides of the boundary.
Give the contract a semantic version in its metadata and keep previous versions importable. Inheritance keeps the diff between versions small and readable:
# contracts/orders.py
"""Data contract for the orders feed. Owner: checkout team."""
import pandera.pandas as pa
from pandera.typing import Series
class OrdersV1(pa.DataFrameModel):
order_id: Series[int] = pa.Field(unique=True, gt=0)
amount: Series[float] = pa.Field(ge=0)
currency: Series[str] = pa.Field(isin=["EUR", "USD"])
class Config:
name = "orders"
coerce = True
metadata = {"contract_version": "1.0.0"}
class OrdersV1_1(OrdersV1):
# additive: a new optional column
channel: Series[str] = pa.Field(nullable=True, isin=["web", "app"])
class Config:
metadata = {"contract_version": "1.1.0"}
class OrdersV2(OrdersV1_1):
# a new currency: old consumers with a fixed EUR/USD mapping will break
currency: Series[str] = pa.Field(isin=["EUR", "USD", "GBP"])
class Config:
metadata = {"contract_version": "2.0.0"}
Whether a change is breaking depends on whose point of view you take. For consumers, the question is: can data that is valid under the new contract break code that was written against the old one? With that definition:
| Change | Effect on consumers | Version bump |
|---|---|---|
| Add a nullable column | Ignored by existing readers (unless they are strict) | Minor |
| Tighten a range or a set of allowed values | Data becomes a subset of what readers already handle | Minor |
| Remove or rename a column | Readers fail on a missing key | Major |
| Change a dtype | Arithmetic, joins and parsing change behaviour | Major |
| Make a column nullable | Readers that assumed presence get missing values | Major |
| Widen allowed values (new category) | Exhaustive mappings and lookups fail | Major |
The last row surprises people. Adding "GBP" looks additive from the producer's side, but any consumer with a fixed currency conversion table now meets a key it does not know. Because a Pandera schema is an object, you can compute these differences instead of arguing about them:
# contracts/compat.py
import pandera.pandas as pa
def breaking_changes(old: pa.DataFrameSchema, new: pa.DataFrameSchema) -> list[str]:
"""Ways in which data valid under `new` can break a consumer written for `old`."""
problems = []
for name, col in old.columns.items():
if name not in new.columns:
problems.append(f"column removed: {name}")
continue
new_col = new.columns[name]
if str(new_col.dtype) != str(col.dtype):
problems.append(f"dtype changed: {name} {col.dtype} -> {new_col.dtype}")
if new_col.nullable and not col.nullable:
problems.append(f"became nullable: {name}")
old_vals, new_vals = _allowed(col), _allowed(new_col)
if old_vals is not None and (new_vals is None or not new_vals <= old_vals):
problems.append(f"allowed values widened: {name}")
return problems
def _allowed(col) -> set | None:
for check in col.checks:
if check.name == "isin":
return set(check.statistics["allowed_values"])
return None
def version(model) -> tuple[int, int, int]:
meta = next(iter(model.get_metadata().values()))["dataframe"]
major, minor, patch = meta["contract_version"].split(".")
return int(major), int(minor), int(patch)
from contracts.orders import OrdersV1, OrdersV1_1, OrdersV2
from contracts.compat import breaking_changes, version
for old, new in [(OrdersV1, OrdersV1_1), (OrdersV1_1, OrdersV2)]:
print(version(old), "->", version(new), breaking_changes(old.to_schema(), new.to_schema()))
(1, 0, 0) -> (1, 1, 0) []
(1, 1, 0) -> (2, 0, 0) ['allowed values widened: currency']
The function covers the common cases; extend it for the checks your contracts actually use.
Package the contract module separately, for example as myproject-contracts on an internal package index, so consumers can pin myproject-contracts>=1.1,<2. The producer validates output against the latest version before publishing. Each consumer validates input against the version it was written for. When the producer releases 2.0.0, it keeps publishing data that also satisfies 1.x for an agreed period (often as a separate table or column), consumers migrate, and only then is 1.x retired. That handshake is the contract; the schema makes it checkable.
Contracts only help if they cannot drift silently. Three kinds of tests cover most of the risk: a stored sample extract must satisfy the current contract, known-bad data must be rejected, and every version step must follow the versioning rule.
# tests/test_orders_contract.py
from pathlib import Path
import pandas as pd
import pandera.pandas as pa
import pytest
from contracts.compat import breaking_changes, version
from contracts.orders import OrdersV1, OrdersV1_1, OrdersV2
FIXTURES = Path(__file__).parent / "fixtures"
HISTORY = [OrdersV1, OrdersV1_1, OrdersV2]
CURRENT = HISTORY[-1]
def test_sample_extract_satisfies_current_contract():
df = pd.read_csv(FIXTURES / "orders_sample.csv")
CURRENT.validate(df, lazy=True)
def test_negative_amount_is_rejected():
df = pd.DataFrame({"order_id": [1], "amount": [-1.0],
"currency": ["EUR"], "channel": [None]})
with pytest.raises(pa.errors.SchemaErrors):
CURRENT.validate(df, lazy=True)
@pytest.mark.parametrize("old,new", list(zip(HISTORY, HISTORY[1:])))
def test_breaking_changes_bump_major(old, new):
breaking = breaking_changes(old.to_schema(), new.to_schema())
if breaking:
assert version(new)[0] > version(old)[0], breaking
else:
assert version(new) > version(old)
$ python -m pytest -q tests
.... [100%]
4 passed in 1.37s
To check that the guard works, we temporarily labelled OrdersV2 as 1.2.0. The run then failed with AssertionError: ['allowed values widened: currency'], which is exactly the review conversation you want to force: either the change is reverted, or the major version goes up and consumers are told.
In the CI configuration, run these tests on every pull request that touches the contracts package, and run the sample-extract test on a schedule against a fresh anonymised extract from the producer. The scheduled run is what catches changes the producer did not announce.
validate accepts head, tail and sample arguments. On very large tables, validate the schema fully and run data checks on a sample, and accept that rare defects may pass.apply with a Python function per row will dominate the runtime.PANDERA_VALIDATION_ENABLED=False. If you use that for a hot path, document it and keep validation enabled in tests and in the batch pipeline.DataFrameModel for every dataset that enters your system from outside, with strict = True and coerce = True.lazy=True in pipelines and store failure_cases for every failed batch.DataFrame objects at boundaries, or set PANDERA_VALIDATION_DEPTH=SCHEMA_AND_DATA knowingly.breaking_changes so that widening a numeric range (for example raising the upper bound of amount) is reported, and add a contract version that triggers it.Found a mistake in this tutorial? Let us know and we will fix it.