Sub topic 17
Migrating a Codebase Incrementally
This chapter assumes you know pandas well, can read Polars expressions (select, with_columns, filter, group_by), and have seen from_pandas, to_pandas and scan_csv. It covers how to move a real codebase from pandas to Polars in stages, without a rewrite that freezes feature work.
Why incremental beats a rewrite
A full rewrite means every pipeline changes at once. Any difference in null handling, sort order or dtypes then shows up as one large, hard-to-diagnose diff. An incremental migration moves one unit at a time and checks each unit against the old output.
The main risks are these:
- Silent behavior differences, such as
NaNversus null, or unstable row order. - Conversion cost at the boundaries between the libraries.
- Code that mixes both libraries, so readers can't tell which type a variable holds.
- Dependencies that only accept pandas, such as some plotting or modeling libraries.
Choose the order of migration
Not every part of a codebase gains the same from Polars. Rank candidates by benefit and risk.
| Candidate | Benefit | Risk | Suggested order |
|---|---|---|---|
| Large CSV or Parquet ingestion | High, because `scan_*` reads only needed data | Low | First |
| Heavy group-by and join steps | High | Medium | Early |
| Row-wise `apply` code | High, once rewritten as expressions | Medium | Early |
| Small lookups and config tables | Low | Low | Opportunistic |
| Code feeding scikit-learn or plotting | Low | High | Last, convert at the boundary |
| Code that depends on index semantics | Low | High | Last, redesign first |
Start at the edges of the pipeline. Input steps often read the most data, and output steps often have a clear contract, such as a file or a table.
The migration loop
Repeat the same loop for each unit, such as a function or a pipeline stage.
- Pick one function with a clear input and output.
- Save its current pandas output as the reference.
- Write the Polars version beside it.
- Compare the two outputs.
- Switch callers, then delete the old version.
Draw boundaries around functions
Keep each function in one library. Convert only where data crosses from a migrated function to an unmigrated one. This makes the type of every variable predictable.
A migrated function can wrap the old interface so that existing callers keep working:
import pandas as pd
import polars as pl
def revenue_by_region(orders: pl.DataFrame) -> pl.DataFrame:
"""New implementation. Works only with Polars."""
return (
orders.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
.group_by("region")
.agg(pl.col("total").sum().alias("revenue"))
.sort("revenue", descending=True)
)
def revenue_by_region_pandas(orders: pd.DataFrame) -> pd.DataFrame:
"""Compatibility shim for callers that still pass pandas."""
result = revenue_by_region(pl.from_pandas(orders))
return result.to_pandas()
if __name__ == "__main__":
sample = pd.DataFrame(
{"region": ["N", "S", "N"], "price": [10.0, 5.0, 20.0], "qty": [2, 3, 10]}
)
print(revenue_by_region_pandas(sample))The shim lets you migrate the implementation first and the callers later. When the last caller moves to Polars, delete the shim. Note that to_pandas needs pyarrow installed.
Control conversion cost
Every conversion has a cost, and a pipeline that bounces between libraries can lose its speed gain.
- Convert once per boundary, not once per operation.
- Convert late when going to pandas, after filtering and aggregating, so fewer rows cross.
- Select only needed columns before converting.
- Avoid conversions inside loops.
import pandas as pd
import polars as pl
lf = pl.LazyFrame(
{
"region": ["N", "S", "N"],
"qty": [1, 2, 3],
"notes": ["a", "b", "c"],
}
)
# Reduce first, then cross the boundary once.
small: pd.DataFrame = (
lf.filter(pl.col("qty") > 1)
.select("region", "qty")
.collect()
.to_pandas()
)
print(small)Handle index-dependent code
Polars has no index, so code that relies on one needs a redesign before it can move. Typical cases:
- A meaningful index, such as a date or an ID, becomes an ordinary column. When you call
from_pandas, passinclude_index=Trueto keep it as a column, or callreset_index()first. - Code that aligns two Series by index becomes an explicit join on a key column.
.loclabel lookups becomefilteron a column value.- A
MultiIndexbecomes several key columns.
Do this redesign in pandas first if the code is complicated. Turn the index into a column, confirm the tests still pass, and then translate the cleaned-up code.
Keep behavior differences visible
Several differences cause most surprises during migration. Record them in your migration notes and add a test for each.
- Row order. Polars
group_bydoes not guarantee group order unless you passmaintain_order=True. Sort explicitly where order matters. - Null and NaN. pandas often treats both as missing. Polars treats
nullandNaNas different values, sofill_nulldoes not touchNaN. - Dtypes. A pandas integer column with missing values becomes
float64. In Polars it stays an integer with nulls. - Strings. pandas
objectcolumns becomepl.String. Mixed-type object columns fail to convert, and you must clean them first. - Mutation. Code that depends on in-place assignment must return new frames instead.
Check progress and prevent regressions
Make the migration measurable. A simple script can report how much of the code still imports pandas:
import pathlib
import re
pattern = re.compile(r"^\s*(import pandas|from pandas)", re.MULTILINE)
remaining = [
path
for path in pathlib.Path("src").rglob("*.py")
if pattern.search(path.read_text(encoding="utf-8"))
]
print(f"{len(remaining)} files still import pandas")
for path in sorted(remaining):
print(f" {path}")Run it in continuous integration and fail the build if the count goes up. Files that are already migrated then stay migrated. Also add type hints (pl.DataFrame versus pd.DataFrame) to every function signature, so a reader can see which library a function expects.
Common errors
- Converting inside a loop. Calling
from_pandason each iteration is slow. Hoist it out of the loop. - Assuming index survives. After
from_pandas, the pandas index is dropped unless you ask for it. - Mixing types in one expression. A
pd.Seriespassed into a Polars expression is not treated as a column. Usepl.Seriesor a column name. - Mutating a frame and ignoring the return value.
df.with_columns(...)without assignment changes nothing. - Deleting the old code too early. Keep the pandas version until the comparison has run on realistic data, including empty inputs and inputs with nulls.
Exit criteria for each unit
A unit counts as migrated when all of these hold:
- The Polars function has type hints and no pandas import.
- A test compares its output with the saved pandas reference.
- Edge cases are covered: empty frame, all-null column, duplicate keys.
- Callers pass Polars frames, or use a shim that is on a removal list.
- The old implementation is deleted.
Exercise
A function takes a pandas DataFrame, filters it, groups it, and passes the result to a plotting library that only accepts pandas. You want to migrate the filter and group steps. Where do you convert, and why?
Show answer
Migrate the function to Polars and convert once at the end, after filtering and grouping, with to_pandas() just before the call to the plotting library. Converting late means only the small aggregated result crosses the boundary. If other callers still pass pandas, wrap the new function in a shim that calls pl.from_pandas on entry. Remove the shim once those callers have migrated.
Exercise
A migrated function returns the same group totals as the pandas version, but your test fails because the rows come back in a different order. What are two correct ways to fix the comparison or the code?
Show answer
Either sort both outputs on the group key before comparing, or call group_by(..., maintain_order=True) if the original order is part of the function's contract. If order matters to callers, an explicit .sort(...) in the function is the more reliable choice, because it states the requirement instead of relying on grouping behavior.