Sub topic 17
Migrating a codebase incrementally
This chapter assumes you know the Polars expression model, the lazy API, and the pandas conversion functions covered earlier. It also assumes the code you are migrating is under version control and has some tests.
Why not rewrite everything at once
A full rewrite mixes two kinds of change: a new library and new behavior. When results differ, you can't tell which kind caused it. An incremental migration keeps the program working after every step, so each difference points to a small change.
Move the boundary outward
Treat the code as a pipeline of functions that pass DataFrames. Pick one function at a time and convert it to Polars. Wrap it in a thin adapter so its callers still see pandas. Once its callers are migrated, delete the adapter.
A worked step
The Polars function holds the real logic. The adapter converts at the boundary.
import pandas as pd
import polars as pl
def revenue_by_region(orders: pl.DataFrame) -> pl.DataFrame:
return (
orders.lazy()
.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
.group_by("region")
.agg(pl.col("total").sum().alias("revenue"))
.sort("region")
.collect()
)
def revenue_by_region_pandas(orders: pd.DataFrame) -> pd.DataFrame:
# Temporary adapter: delete it when no pandas callers remain.
return revenue_by_region(pl.from_pandas(orders)).to_pandas()
if __name__ == "__main__":
pdf = pd.DataFrame(
{
"region": ["east", "west", "east"],
"price": [10.0, 20.0, 5.0],
"qty": [3, 1, 4],
}
)
print(revenue_by_region_pandas(pdf))to_pandas needs pyarrow installed. Existing callers keep calling revenue_by_region_pandas and don't change.
Choosing the order
- Start with leaf functions that have few callers and clear inputs and outputs.
- Prefer steps that are slow or memory-heavy today, such as large group-bys and joins. They give the biggest gain.
- Migrate file reading last among the early steps. Then switch to
scan_csvorscan_parquetso the optimizer sees the whole query. - Leave code that depends on an index, or on libraries that only accept pandas, until the end.
Common errors
- Converting in the middle of a loop. Each
from_pandasorto_pandascall copies data and can convert dtypes. Convert once per function boundary, not per row or per batch. - Losing the index. Polars has no index, so a pandas index doesn't survive the trip. Call
reset_index()before converting if the index carries data. - Silent NaN changes. pandas often uses NaN for missing values. Check how missing values arrive on the Polars side before you filter on them.
- Changing logic and library together. Keep each migration step a pure translation. Fix bugs in a separate commit.
Exercise
You migrated a function to Polars and added an adapter that converts to and from pandas. Name two situations where you can delete the adapter.
Show answer
Delete it when every caller of the function has been migrated to Polars, or when the function's inputs and outputs no longer need to be pandas, for example because the code that loads the data and the code that uses the result are both Polars. At that point the adapter only adds copies.