Sub topic 18
Validating Migrated Results
This chapter assumes you can read pandas and Polars code, know the difference between null and NaN, and have already ported at least one pipeline. It covers how to check that the Polars version of a pipeline produces the same answer as the pandas original, and how to handle the differences that are expected.
Why validation needs a plan
A migrated pipeline that runs without errors can still return wrong numbers. Most mismatches come from a small set of causes:
- Row order. pandas group-bys sort keys by default. Polars
group_bydoes not guarantee any order. - Index. pandas carries an index, and Polars has none. A frame with a leftover index can compare differently.
- Dtypes. A pandas
int64column with missing values becomesfloat64. Polars keepsInt64and stores a null. - Missing values. pandas often uses NaN for "missing". Polars separates null from NaN.
- Floating-point sums. Different summation order can change the last digits.
Validation means comparing the two outputs after you account for each of these, and deciding which differences are acceptable.
Comparing whole frames
Polars ships a testing module. assert_frame_equal raises an AssertionError that describes the first difference it finds. The usual approach is to convert the pandas result into Polars and compare there.
import polars as pl
from polars.testing import assert_frame_equal
expected = pl.from_pandas(pandas_result.reset_index(drop=True))
assert_frame_equal(polars_result, expected, check_row_order=False)
# Convert back to pandas at a boundary that still needs it
pdf_again = polars_result.to_pandas()This snippet assumes pandas_result and polars_result already exist. reset_index(drop=True) removes the pandas index so it is not converted into a column. to_pandas needs pyarrow installed.
The main parameters of assert_frame_equal are these:
| Parameter | Default | Use it when |
|---|---|---|
| `check_row_order` | `True` | Set to `False` when the original order was an accident of pandas, such as group-by sorting. |
| `check_column_order` | `True` | Set to `False` if column order does not matter to consumers. |
| `check_dtypes` | `True` | Set to `False` only for a known, accepted dtype difference. |
| `check_exact` | `False` | Set to `True` for integers, strings and anything that must match exactly. |
| `rel_tol` and `abs_tol` | `1e-5` and `1e-8` | Loosen or tighten for floating-point columns. |
Keep check_dtypes=True as long as you can. A dtype mismatch often points to a real porting issue, such as a column that silently became Float64 in one version.
Making the comparison fair
Sort by a key
If row order is not part of the contract, sorting both sides by the same key columns is more reliable than turning the order check off. It also catches duplicate keys, because tied rows still differ in order.
import polars as pl
from polars.testing import assert_frame_equal
def compare_sorted(actual: pl.DataFrame, expected: pl.DataFrame, keys: list[str]) -> None:
actual_sorted = actual.sort(keys)
expected_sorted = expected.sort(keys)
assert_frame_equal(actual_sorted, expected_sorted)
left = pl.DataFrame({"region": ["west", "east"], "revenue": [10.0, 20.0]})
right = pl.DataFrame({"region": ["east", "west"], "revenue": [20.0, 10.0]})
compare_sorted(left, right, ["region"])
print("frames match")With a unique key, sorting makes the comparison fully deterministic. If the key is not unique, add more columns to keys until it is.
Align dtypes deliberately
When a difference is expected, cast one side explicitly and say why. This keeps the exception visible in the code.
import pandas as pd
import polars as pl
from polars.testing import assert_frame_equal
pandas_result = pd.DataFrame({"id": [1, 2, 3], "score": [0.5, None, 0.7]})
polars_result = pl.DataFrame({"id": [1, 2, 3], "score": [0.5, None, 0.7]})
expected = pl.from_pandas(pandas_result, nan_to_null=True)
assert_frame_equal(polars_result, expected)
print("frames match")nan_to_null=True is the default in from_pandas, so NaN values in a pandas float column become null. This is usually what you want if the original code treated NaN as "missing". If NaN in the original data was a real floating-point NaN, for example from 0/0, pass nan_to_null=False and compare NaN against NaN.
Checking missing values separately
Whole-frame equality is a blunt tool. A pair of targeted checks on null and NaN counts makes a failure easier to diagnose.
import polars as pl
def missing_report(df: pl.DataFrame) -> pl.DataFrame:
return df.select(
[pl.col(c).null_count().alias(f"{c}__nulls") for c in df.columns]
)
df = pl.DataFrame({"x": [1.0, None, float("nan")], "y": ["a", None, "c"]})
print(missing_report(df))Compare this report for the pandas-derived and Polars frames. A column where pandas reports isna().sum() == 2 and Polars reports one null means one value was NaN and is now not counted as missing. The cause is the null versus NaN split from the earlier chapter, not a data loss.
Checking cheap invariants first
Before comparing every cell, check properties that are quick to compute and that point to the failing step.
import polars as pl
def invariants(actual: pl.DataFrame, expected: pl.DataFrame, keys: list[str]) -> list[str]:
problems = []
if actual.shape != expected.shape:
problems.append(f"shape {actual.shape} != {expected.shape}")
if set(actual.columns) != set(expected.columns):
problems.append("column sets differ")
if actual.select(pl.struct(keys).is_duplicated().any()).item():
problems.append("duplicate keys in actual")
return problems
a = pl.DataFrame({"id": [1, 2], "v": [1.0, 2.0]})
b = pl.DataFrame({"id": [1, 2], "v": [1.0, 2.0]})
print(invariants(a, b, ["id"]))A row-count mismatch right after a join usually means the join type or key handling changed. A duplicated key after a group-by means the grouping columns are not what you meant.
Validating at each step
For a long pipeline, compare intermediate frames, not only the final one. A practical layout is:
- Run the pandas pipeline and save the output of each stage to Parquet.
- Run the Polars pipeline, then load each saved stage with
pl.read_parquet. - Compare stage by stage and stop at the first mismatch.
import polars as pl
from polars.testing import assert_frame_equal
def check_stage(name: str, actual: pl.DataFrame, path: str, keys: list[str]) -> None:
expected = pl.read_parquet(path)
try:
assert_frame_equal(actual.sort(keys), expected.sort(keys))
except AssertionError as exc:
raise AssertionError(f"stage {name!r} differs from {path}") from excStopping at the first failing stage tells you which port to inspect. Without this, a mistake in an early filter shows up as a baffling difference after three joins.
Testing with realistic data
Tests on a tiny hand-built frame miss problems that appear with real data. Include these cases in your comparison data:
- Rows with null keys, which behave differently in joins and groups.
- Empty groups and an empty input frame.
- Duplicate keys on the right side of a join.
- Strings with leading whitespace or mixed case.
- Timezone-aware and naive datetimes.
- Very large and very small floats.
Run the comparison on a sample of production data as well, not only on test fixtures.
Common errors
- Comparing with
==. Usingdf1.equals(df2)ordf1 == df2gives a result that hides which cell differs. Useassert_frame_equal. - Forgetting
reset_index. The pandas index becomes an extra column, or is dropped, depending on how you convert. - Loosening tolerance until the test passes. Raising
abs_tolhides a real bug if the difference is not floating-point noise. Inspect the differing values first. - Disabling
check_dtypesglobally. Cast the specific columns instead. - Validating only the happy path. Empty and null cases are where ports usually diverge.
What to do with an expected difference
Some differences are not bugs. A group-by that returns a different order, or a column that is now Int64 rather than float64, can be accepted. Record each one as a short comment next to the test, with the reason. Without this record, the next person to touch the code cannot tell a deliberate difference from a regression.
Exercise
A migrated pipeline fails assert_frame_equal on a column of float sums, and the reported difference is in the 12th decimal place. The rest of the frame matches. What should you do, and what should you avoid?
Show answer
Confirm the difference is floating-point noise by inspecting the differing values, then keep check_exact=False and set a suitable rel_tol or abs_tol for that comparison. Avoid disabling check_dtypes or the whole comparison, and avoid raising the tolerance far beyond the observed noise, because that could hide a real error.
Exercise
After migrating a group-by, the row counts match but assert_frame_equal fails on the first row. Both frames contain the same groups. What is the likely cause, and how do you fix the comparison?
Show answer
Polars group_by does not guarantee output order, while pandas sorted the keys by default. Sort both frames by the key columns before comparing, or pass check_row_order=False. Sorting by a unique key is more reliable.