Your Polars job reads orders.parquet, filters out negative amounts, and writes the
rest. A week later someone asks why 300 orders are missing from the report. The filter worked. Nobody
kept the rows it dropped, or a note of why.
Validation in a DataFrame pipeline usually starts as a few filter calls. Each check
answers "is this row OK?", but the questions that come later (which rule did it break, where did it go,
do the counts add up) need structure the first version did not have.
This guide compares the realistic options for checking data quality in Polars, from plain expressions to schema libraries to contracts, with what each does with failing rows. It ends with when a contract is worth adding and when it is not. Tool descriptions come from each project's documentation; check them for your version.
The question that separates the options
Every option below can tell you that data is wrong. They differ on three things:
- Fail or split: does validation raise an error, or return passing and failing rows separately?
- Reason per row: can you see which rule each failing row broke?
- Where rules live: Python code, a class, or a file other tools can read?
Option 1: plain Polars expressions
You can build a reason column yourself with expressions. This is a reasonable pattern and needs no extra dependency:
import polars as pl checks = { "amount_negative": pl.col("amount") < 0, "status_unknown": ~pl.col("status").is_in(["pending", "shipped", "delivered", "returned"]), "order_id_missing": pl.col("order_id").is_null(), } df = pl.read_csv("orders.csv").with_columns( pl.concat_list([pl.when(e).then(pl.lit(n)) for n, e in checks.items()]) .list.drop_nulls().alias("errors") ) good = df.filter(pl.col("errors").list.len() == 0).drop("errors") bad = df.filter(pl.col("errors").list.len() > 0)
Fits: a few rules in one pipeline. Watch for: null handling (a null
status makes is_in return null, so the row can slip through unless you
handle it), copying the pattern into every job, and rules that exist only in code.
Option 2: schema libraries for Polars
| Library | Rules defined as | Failing rows |
|---|---|---|
| Pandera | DataFrameModel class or schema object | Raises; lazy mode collects all errors |
| Patito | Pydantic model | Raises with per-column messages |
| dataframely | Schema class with rule methods | filter splits; failure info per rule |
Pandera
added Polars support in 0.19.0. It validates both DataFrame and LazyFrame;
on a LazyFrame it checks only schema-level properties unless you opt into data checks. With
lazy=True it collects every error into one exception instead of stopping at the first.
Good fit if you already use Pandera on pandas or want type-checked function signatures.
Patito uses a Pydantic
model as the DataFrame schema. Model.validate(df) checks types, missing columns, uniqueness,
allowed literals, bounds and regex, and raises a readable error. Model.examples() builds
valid test frames, which is handy for unit tests.
dataframely, from
QuantCo, is a Polars-native schema library. Beyond validate, its
filter method returns the passing rows plus a
FailureInfo object with the failing rows and counts per rule. That
is the closest of the three to a quarantine split.
All three keep rules in Python classes, close to the code that uses them. That is a strength for a single codebase and a limit when the same rules must be read by another engine or another team.
Option 3: Great Expectations
Great Expectations offers a large Expectation library, alerting and Data Docs. Its
documented DataFrame sources are pandas and Spark, not Polars, so a Polars
pipeline converts the frame or validates files or SQL tables instead. It reports failures (with row
detail under the COMPLETE result format) rather than splitting the frame. If you are weighing
a move, see
Moving from Great Expectations to data contracts.
Option 4: a data contract
A contract keeps the schema and the rules in a YAML file, and a runtime applies them. With
LakeLogic
(open source, Apache 2.0; Polars is in the base install and is the default engine), a run returns
passing rows and quarantined rows, each with a _lakelogic_errors list. Same five made-up
orders as above:
version: 1.0.0 info: title: Orders model: fields: - name: order_id type: string required: true - name: customer_id type: string required: true - name: amount type: float min: 0 - name: status type: string accepted_values: [pending, shipped, delivered, returned] - name: order_date type: date quality: row_rules: - regex_match: field: order_id pattern: "^ORD-[0-9]{4}$"
from lakelogic import DataProcessor result = DataProcessor("orders.yaml").run_source("orders.csv") print(result.good_count, result.bad_count) for row in result.bad.select(["order_id", "_lakelogic_errors"]).to_dicts(): print(row) # 2 3 # {'order_id': 'ORD-1002', '_lakelogic_errors': ['Rule failed: amount_range ("amount" >= 0.0)']} # {'order_id': 'ORD-1003', '_lakelogic_errors': ['Rule failed: status_accepted_values ("status" IN (...))']} # {'order_id': None, '_lakelogic_errors': ['Rule failed: order_id_required ("order_id" IS NOT NULL)', # 'Rule failed: order_id_regex_match (regexp_like(...))']}
The status list is shortened for width. result.good and result.bad are Polars
DataFrames, and here the two counts add up to the five source rows. From the command line,
lakelogic run --contract orders.yaml --source orders.csv --output-bad bad.parquet writes
the quarantined rows with their reasons. (In our run, writing the bad rows to CSV failed because the
reasons column is a list; use Parquet.)
Two details worth knowing. Dataset rules such as unique are evaluated over the whole
batch and reported as a pass or fail for the run; they do not move rows to quarantine. And
infer_contract("orders.parquet", title="Orders") drafts a contract from existing data,
which you then review and edit.
Where a contract adds value
- Rules readable outside Python. The YAML can be reviewed by people who do not read the pipeline code.
- One definition, several engines. The same file runs on DuckDB with
engine="duckdb"; in our run it produced the same split. Spark, Snowflake and BigQuery engines also exist, so a Polars prototype can move without rewriting rules. See Stop the Spark tax. - Quarantine as the default. Failing rows are kept with reasons, so dropped data stays explainable.
When you do not need one
- A handful of checks in one script. Option 1 is fine; add a reason column and keep the bad rows.
- You want failures to stop the job and types checked at function boundaries. Pandera or Patito fit that well.
- You want a Polars-native split in Python. dataframely's
filterdoes that without a separate file. - Your team runs pandas. LakeLogic has no pandas engine.
Limits
A passing run shows the data met the rules you wrote, not that the rules are complete or the numbers are right. The example is five rows on one machine; we make no performance comparison between these tools.
Key takeaways
- Decide first whether failing rows should stop the job or be split off with a reason.
- Plain expressions work; handle nulls explicitly and keep the dropped rows.
- Pandera and Patito raise; dataframely and LakeLogic can split passing from failing rows.
- A contract earns its place when rules must be shared across engines or teams.
Run the example in your browser
The quickstart notebook runs a contract on Polars and shows the quarantined rows. No install needed.