DEV Community

Cover image for Validate Pandas DataFrames with Pandera
Muhammad Saud
Muhammad Saud

Posted on Originally published at logicstack.org

Validate Pandas DataFrames with Pandera

Pandera is an open-source Python library that checks a pandas DataFrame against a schema you write. You describe the columns, types and rules once, and Pandera checks every row, naming the column, the rule and the failing values when data breaks it. It turns silent data bugs into loud, precise errors where bad data enters your code.

Key takeaways

  • A Pandera schema is a contract for a DataFrame: column names, data types, value ranges and allowed categories in one place.
  • Validating returns the DataFrame when data passes and raises a SchemaError that names the exact failing values when it does not.
  • Lazy validation collects every failure into one failure_cases table instead of stopping at the first bad value.
  • The class-based DataFrameModel API reads like a Pydantic model and supports cross-column rules such as revenue greater than zero.
  • The check_types decorator validates the inputs and outputs of a pipeline function, so bad data never slips through between steps.

What we build

We build a validation layer for a small orders table. We write a schema for six columns, run it against a clean CSV and a dirty CSV, collect every error in one report, then rewrite the schema as a class and wire it into a revenue pipeline with the check_types decorator. Every script below ran on our machine with Python 3.12.3, pandas 3.1.1 and Pandera 0.36.0, and every output block is the real output of that script.

Prerequisites

  • Python 3.10 or newer and pip. Pandera 0.36 requires Python 3.10 or newer, according to the official Pandera documentation.
  • Basic pandas: reading a CSV and selecting columns.
  • No account, no API key, no database. Everything runs locally.

Step 1: Install Pandera and check the versions

We install Pandera with the pandas extra, which pulls in pandas if it is missing. Then we print the versions so we know exactly what ran.

python3 -m venv venv
source venv/bin/activate
pip install "pandera[pandas]"
python -c "import pandera, pandas; print(pandera.__version__, pandas.__version__)"
Enter fullscreen mode Exit fullscreen mode
0.36.0 3.1.1
Enter fullscreen mode Exit fullscreen mode

Since Pandera 0.24, the recommended import for pandas schemas is import pandera.pandas as pa. The old top-level import still works for now but is being phased out, so new code should use the explicit path.

Step 2: What does a schema look like?

We start with two small files. orders.csv holds four clean orders. bad_orders.csv holds five orders with deliberate faults: a duplicate order id, an email with no at sign, a negative quantity, a zero price and a status value that does not exist. The schema in schema_def.py describes what valid data looks like.

import pandera.pandas as pa
from pandera.pandas import Column, Check, DataFrameSchema

schema = DataFrameSchema(
    {
        "order_id": Column(int, Check.gt(0), unique=True),
        "customer_email": Column(str, Check.str_contains("@")),
        "product": Column(str, Check.isin(["Widget", "Gadget", "Doohickey"])),
        "quantity": Column(int, Check.gt(0)),
        "unit_price": Column(float, Check.in_range(0.01, 10000)),
        "status": Column(str, Check.isin(["paid", "shipped", "refunded"])),
    },
    strict=True,
)
Enter fullscreen mode Exit fullscreen mode

Each column gets a type and one or more checks. Check.gt(0) means strictly greater than zero. Check.isin limits a column to a fixed list of values. unique=True forbids duplicate order ids. The strict=True flag rejects any column that is not in the schema, which catches renamed or extra columns from a changed export.

Step 3: How does Pandera report a bad row?

We validate both files with step_schema.py. A passing DataFrame comes back unchanged. A failing one raises a SchemaError that names the problem.

import pandas as pd
import pandera.pandas as pa
from schema_def import schema

good = pd.read_csv("orders.csv")
validated = schema.validate(good)
print("good rows:", len(validated))

bad = pd.read_csv("bad_orders.csv")
try:
    schema.validate(bad)
except pa.errors.SchemaError as err:
    print("SchemaError:", err)
Enter fullscreen mode Exit fullscreen mode
good rows: 4
SchemaError: series 'order_id' contains duplicate values:
0    101
1    101
Name: order_id, dtype: int64
Enter fullscreen mode Exit fullscreen mode

The error names the column, the rule and the exact rows. Instead of a wrong total appearing three steps later, the pipeline stops here with a message a human can act on. But the bad file has five faults and we saw only the first one: Pandera stops at the first failure by default, which is fine for a quick check but slow for cleaning a dirty file.

Step 4: How do we collect every error at once?

Pass lazy=True and catch SchemaErrors, plural. Its failure_cases attribute is a DataFrame with one row per failure, naming the column, the check and the failing value. We run it with step_lazy.py.

import pandas as pd
from pandera.errors import SchemaErrors
from schema_def import schema

bad = pd.read_csv("bad_orders.csv")
try:
    schema.validate(bad, lazy=True)
except SchemaErrors as err:
    print(err.failure_cases.to_string(index=False))
    print("total failures:", len(err.failure_cases))
Enter fullscreen mode Exit fullscreen mode
schema_context         column                                 check check_number   failure_case  index
        Column       order_id                      field_uniqueness         None            101      0
        Column       order_id                      field_uniqueness         None            101      1
        Column customer_email                     str_contains('@')            0 benexample.com      1
        Column       quantity                       greater_than(0)            0             -1      1
        Column       quantity                       greater_than(0)            0              0      4
        Column     unit_price                 in_range(0.01, 10000)            0            0.0      4
        Column         status isin(['paid', 'shipped', 'refunded'])            0           lost      2
total failures: 7
Enter fullscreen mode Exit fullscreen mode

One run found all seven failures across five columns, including both copies of the duplicated order id at rows 0 and 1. The index column points back at the original rows, so we can fix the source file instead of guessing. In a real pipeline we would save this table as a report for whoever produced the data.

Step 5: Why use the class-based DataFrameModel?

For a schema that lives in a real project, the class-based API reads better. It mirrors the Pydantic pattern of defining schemas as Python classes, which makes them self-documenting and easier to maintain as the project grows. It also supports rules that span columns. Our step_model.py rewrites the same orders schema as a class and adds one cross-column rule: revenue, quantity times unit price, must be greater than zero.

import pandas as pd
import pandera.pandas as pa
from pandera.typing import DataFrame, Series

class Order(pa.DataFrameModel):
    order_id: Series[int] = pa.Field(gt=0, unique=True)
    customer_email: Series[str] = pa.Field(str_contains="@")
    product: Series[str] = pa.Field(isin=["Widget", "Gadget", "Doohickey"])
    quantity: Series[int] = pa.Field(gt=0)
    unit_price: Series[float] = pa.Field(ge=0.01, le=10000)
    status: Series[str] = pa.Field(isin=["paid", "shipped", "refunded"])

    @pa.dataframe_check
    def revenue_not_negative(cls, df: DataFrame["Order"]) -> Series[bool]:
        return (df["quantity"] * df["unit_price"]) > 0
Enter fullscreen mode Exit fullscreen mode

Each column is a type annotation with a Field for its rules, and a method decorated with @pa.dataframe_check adds a rule across columns. Both APIs run the same checks, so the choice is about readability, not power.

Step 6: How do we validate a whole pipeline function?

A schema that only runs when someone remembers to call it will be forgotten. The @pa.check_types decorator validates the inputs and outputs of a pipeline function using normal type hints, so every call is checked. We add a revenue step to the same file.

@pa.check_types
def add_revenue(df: DataFrame[Order]) -> DataFrame[Order]:
    out = df.copy()
    out["revenue"] = out["quantity"] * out["unit_price"]
    return out

good = pd.read_csv("orders.csv")
result = add_revenue(good)
print(result[["order_id", "quantity", "unit_price", "revenue"]].to_string(index=False))
print("total revenue: $%.2f" % result["revenue"].sum())

bad = pd.read_csv("bad_orders.csv")
try:
    add_revenue(bad)
except Exception as err:
    print(type(err).__name__, "->", str(err).splitlines()[0])
Enter fullscreen mode Exit fullscreen mode
order_id  quantity  unit_price  revenue
      101         2       29.99    59.98
      102         1       49.99    49.99
      103         5       29.99   149.95
      104         3       19.99    59.97
total revenue: $319.89
SchemaError -> series 'order_id' contains duplicate values:
Enter fullscreen mode Exit fullscreen mode

The clean file flows through and the total revenue is $319.89. The dirty file never reaches the calculation: the decorator validates the input first and raises the same SchemaError we saw in step 3. Validate at the edges, right after loading raw data and right before writing results or training a model, and let the decorator guard the steps in between.

Step 7: How do we fix string numbers with coerce?

CSV files have no types, so a column of numbers often arrives as strings. With coerce=True, Pandera converts types before the checks run, so amounts stored as strings become floats. We test it in step_coerce.py with a frame where every value is a string.

import pandas as pd
import pandera.pandas as pa
from pandera.pandas import Column, Check, DataFrameSchema

raw = pd.DataFrame({
    "order_id": ["201", "202"],
    "quantity": ["2", "3"],
    "unit_price": ["29.99", "19.99"],
})
print("before:", raw.dtypes.to_dict())

schema = DataFrameSchema(
    {
        "order_id": Column(int, Check.gt(0)),
        "quantity": Column(int, Check.gt(0)),
        "unit_price": Column(float, Check.gt(0)),
    },
    coerce=True,
)
clean = schema.validate(raw)
print("after:", clean.dtypes.to_dict())
print(clean.to_string(index=False))
Enter fullscreen mode Exit fullscreen mode
before: {'order_id': StringDtype(storage='python', na_value=nan), 'quantity': StringDtype(storage='python', na_value=nan), 'unit_price': StringDtype(storage='python', na_value=nan)}
after: {'order_id': dtype('int64'), 'quantity': dtype('int64'), 'unit_price': dtype('float64')}
 order_id  quantity  unit_price
      201         2       29.99
      202         3       19.99
Enter fullscreen mode Exit fullscreen mode

Pandas 3 reads text columns as its string dtype by default, so the hand-built frame is all strings. After validation the columns are real integers and floats, and the checks ran on the converted values. One warning: coercion only converts values that can convert. A value like "N/A" in a number column still fails validation, which is what we want. Coercion fixes types, it never hides bad data.

What to try next

  • Point the schema at a real CSV you work with and run lazy validation on it. The failure_cases table usually finds at least one surprise in the first run.
  • Add a nullable column, such as a discount code that may be missing, with Column(str, nullable=True), and check that empty values pass while wrong types still fail.
  • Try the Polars backend. Pandera supports Polars, Dask, Modin and PySpark through the same schema definition, so the schema you wrote here transfers to a bigger pipeline without a rewrite.

Originally published on LogicStack. Run the code examples right in your browser with our free interactive Python and SQL playgrounds — no setup, no sign-up.

Top comments (0)