TL;DR
Pandera checks a pandas DataFrame against a schema you write, and names the column, rule and rows when the data breaks it. This guide builds that check for an orders file step by step, with the real error output at each stage. Negative revenue makes a fine plot twist in a mystery novel, less so in a morning report.
The steps that do the heavy lifting:
Say a nightly job loads an orders file from a partner and writes a revenue report. One morning the report shows negative revenue. Someone traces it back: the partner started sending refunds as negative prices, and a duplicated order ID doubled one customer’s total. Nothing in the pipeline complained, because nothing checked.
Pandera is an open source Python library that checks a pandas DataFrame against a schema you write: which columns must exist, what type each one is, and which values are allowed. When the data breaks a rule, Pandera raises an error that names the column, the rule and the rows that failed. This guide builds that check for the orders file step by step, using Pandera 0.35 and pandas 3.0, and shows the real error output at each stage.
Key Takeaways
- Pandera validates DataFrames against a schema. A failed check raises an error with the column, the check and the failing values.
- In recent versions, import Pandera for pandas with
import pandera.pandas as pa. The top-levelimport panderapath for pandas is being phased out. - You can write schemas as objects (
DataFrameSchema) or as classes (DataFrameModel). Both run the same checks. - Use
lazy=Trueto collect every failure in one pass, instead of stopping at the first one. - Put the check at the boundary where data enters your code, so bad rows stop before they reach a report or a model.
What Is Pandera?
Pandera is a data validation library for DataFrames. It started with pandas and now also supports Polars, PySpark and other backends. The project lives at unionai-oss/pandera on GitHub, and the official documentation covers every check and option.
The idea is simple. You describe what valid data looks like once, and Pandera compares every DataFrame against that description. This is the same idea as type hints for function arguments, applied to the contents of a table.
Step 1: Install Pandera and Check the Import
pip install pandera pandas Pandera 0.24.0 added the pandera.pandas module, and the documentation now recommends it for all pandas schemas. Older tutorials use import pandera as pa. That still works for now but is scheduled for deprecation, so new code should use the explicit path:
import pandas as pd
import pandera.pandas as pa Run pip show pandera to check your version. The examples here ran on Pandera 0.35.0, pandas 3.0.5 and Python 3.13.
Step 2: Write a Schema for the Orders Data
A DataFrameSchema maps each column name to a Column with a type and optional checks. For the orders file, the rules are: order IDs are unique strings, quantity is a whole number of at least 1, unit price is above zero, and the country is one of three markets.
orders_schema = pa.DataFrameSchema(
{
"order_id": pa.Column(str, unique=True),
"quantity": pa.Column(int, pa.Check.ge(1)),
"unit_price": pa.Column(float, pa.Check.gt(0)),
"country": pa.Column(str, pa.Check.isin(["US", "CA", "MX"])),
},
strict=True,
)
good = pd.DataFrame({
"order_id": ["A-1", "A-2", "A-3"],
"quantity": [2, 1, 5],
"unit_price": [9.99, 24.50, 3.25],
"country": ["US", "CA", "MX"],
})
print(orders_schema.validate(good)) strict=True means any column not in the schema is an error. That catches the case where a partner adds or renames a column without telling you. When the data passes, validate returns the DataFrame unchanged:
order_id quantity unit_price country
0 A-1 2 9.99 US
1 A-2 1 24.50 CA
2 A-3 5 3.25 MX Step 3: See What a Failure Looks Like
Now feed it the file from the opening: a duplicate order ID, a quantity of zero, a negative price and a country outside the list.
bad = pd.DataFrame({
"order_id": ["A-1", "A-2", "A-2"],
"quantity": [2, 0, 5],
"unit_price": [9.99, 24.50, -3.25],
"country": ["US", "BR", "MX"],
})
try:
orders_schema.validate(bad)
except pa.errors.SchemaError as err:
print("SchemaError:", err) By default Pandera stops at the first failed check and raises a SchemaError:
SchemaError: series 'order_id' contains duplicate values:
1 A-2
2 A-2
Name: order_id, dtype: str The message tells you the column, the problem and the exact rows. In a scheduled job, that error is the alert. The run fails before it writes a wrong report.
Step 4: Collect Every Error With Lazy Validation
Stopping at the first error is fine in a pipeline, but when you are cleaning a file you want the full list. Pass lazy=True and catch SchemaErrors (plural). Its failure_cases attribute is a DataFrame with one row per failure. The lazy validation docs describe the full report format.
try:
orders_schema.validate(bad, lazy=True)
except pa.errors.SchemaErrors as err:
print(err.failure_cases[["column", "check", "failure_case", "index"]]) column check failure_case index
0 order_id field_uniqueness A-2 1
1 order_id field_uniqueness A-2 2
2 quantity greater_than_or_equal_to(1) 0 1
3 unit_price greater_than(0) -3.25 2
4 country isin(['US', 'CA', 'MX']) BR 1 All four problems from the opening are in one table. You can save it as a CSV, send it back to the partner, or filter the bad rows out. Pandera can also drop invalid rows for you with the drop_invalid_rows option, which requires lazy mode.
Step 5: Write the Same Rules as a Class
A DataFrameModel describes the schema as a Python class with type annotations. Many teams prefer it because it reads like a dataclass and works with type checkers. It also makes rules that span several columns easy to add with @pa.dataframe_check.
Here the orders now carry a discount, and there is a business rule: discounts above 20% are only allowed on orders of 10 or more units. The @pa.check_types decorator validates the input every time the function is called.
import pandas as pd
import pandera.pandas as pa
from pandera.typing import DataFrame, Series
class Orders(pa.DataFrameModel):
order_id: Series[str] = pa.Field(unique=True)
quantity: Series[int] = pa.Field(ge=1)
unit_price: Series[float] = pa.Field(gt=0)
discount: Series[float] = pa.Field(ge=0, le=1, nullable=True)
@pa.dataframe_check
def discount_needs_quantity(cls, df: pd.DataFrame) -> Series[bool]:
# discounts above 20% only on orders of 10 or more units
return (df["discount"].fillna(0) <= 0.2) | (df["quantity"] >= 10)
class Config:
coerce = True
@pa.check_types
def add_revenue(orders: DataFrame[Orders]) -> pd.DataFrame:
out = orders.copy()
out["revenue"] = out["quantity"] * out["unit_price"] * (1 - out["discount"].fillna(0))
return out
raw = pd.DataFrame({
"order_id": ["B-1", "B-2", "B-3"],
"quantity": ["3", "12", "4"], # strings from a CSV
"unit_price": [10.0, 8.0, 5.0],
"discount": [None, 0.25, 0.30],
})
try:
add_revenue(raw)
except pa.errors.SchemaError as err:
print(err)
raw.loc[2, "discount"] = 0.10
print(add_revenue(raw)) Two things happen here. First, coerce = True converts the quantity strings to integers before checking, which is what you usually want for data read from CSV. Second, order B-3 has a 30% discount on 4 units, so the cross-column rule fails:
DataFrameSchema 'Orders' failed element-wise validator number 0: <Check discount_needs_quantity> failure cases: B-3, 4, 5.0, 0.3
order_id quantity unit_price discount revenue
0 B-1 3 10.0 NaN 30.0
1 B-2 12 8.0 0.25 72.0
2 B-3 4 5.0 0.10 18.0 After the discount is corrected to 10%, the function runs and returns the revenue column. The rule lives next to the data definition, not buried in the report code.
Where Should Data Validation Run?
Validate at the boundary: right after you read a file, call an API or query a table you do not control. That is where unexpected changes arrive. A few placements work well in practice:
- On load. Wrap your read function and validate before returning. Every caller then gets clean data or an error.
- Before training a model. Check ranges and missing values so a broken feature does not slip into training. If you scale features afterward, our guide to standardization and min-max scaling covers that next step.
- In tests. Run the schema on sample fixtures in your test suite, so a code change that breaks the output shape fails in CI.
Keep the Pandera version pinned with your other dependencies, since check names and defaults can change between releases. Our article on moving beyond requirements.txt explains one way to do that.
Pandera Checks You Will Use Most
| Need | Check |
|---|---|
| Value range | pa.Check.ge(0), pa.Check.le(100), pa.Check.in_range(0, 100) |
| Allowed values | pa.Check.isin([...]) |
| Text pattern | pa.Check.str_matches(r"^A-\d+$") |
| No duplicates | pa.Column(..., unique=True) |
| Missing values allowed | pa.Column(..., nullable=True) |
| Custom rule | pa.Check(lambda s: ...) or @pa.check / @pa.dataframe_check in a model |
Back to the Negative Revenue Report
With the schema in place, the nightly job from the opening would have stopped at load time with a table listing the duplicated order ID and the negative price, row by row. Nobody would have seen a wrong report, and the fix would have been a message to the partner with the failure table attached. A schema of about ten lines replaced a morning of debugging.
Frequently Asked Questions
Should I Use import pandera or import pandera.pandas?
Use import pandera.pandas as pa for pandas data. It was added in Pandera 0.24.0 and is the path the documentation recommends. The older top-level import still works in current versions but is scheduled for deprecation.
What Is the Difference Between SchemaError and SchemaErrors?
SchemaError is raised at the first failed check, which is the default. SchemaErrors is raised when you pass lazy=True, and it holds every failure in its failure_cases DataFrame. Catch the one that matches how you call validate.
Does Pandera Slow Down My Pipeline?
Built-in checks run as vectorized pandas operations, so they are usually fast compared with reading the data. Custom checks written with Python loops will be slower. For very large tables, you can validate a sample with the head, tail or sample arguments of validate.
Can Pandera Work With Polars or PySpark?
Yes. Pandera has separate modules for Polars, PySpark and other backends, with the same schema ideas. The checks available differ a little by backend, so check the documentation page for the one you use.




