Sub topic 16
Converting between pandas and Polars
This chapter assumes you know pandas DataFrames and have read the earlier chapters on Polars expressions, nulls and dtypes. You will learn to move data between the two libraries at the boundaries of a codebase that is being migrated step by step.
Why conversion matters
You rarely migrate everything at once. Plotting code, scikit-learn pipelines, or a legacy function may still expect pandas. Conversion functions let you keep those parts running while the rest moves to Polars.
| Direction | Function | Requires |
|---|---|---|
| pandas to Polars | `pl.from_pandas(pdf)` | `pyarrow` for most cases |
| Polars to pandas | `df.to_pandas()` | `pyarrow` |
| Polars to NumPy | `df.to_numpy()` | NumPy |
| Series to Series | `pl.from_pandas(pser)` and `s.to_pandas()` | `pyarrow` |
Install the dependencies with pip install polars pandas pyarrow.
Converting a DataFrame
import pandas as pd
import polars as pl
pdf = pd.DataFrame(
{"region": ["north", "south", "north"], "total": [120.0, None, 80.0]},
index=[10, 11, 12],
)
df = pl.from_pandas(pdf)
print(df)
back = df.to_pandas()
print(back)Polars has no index, so the index values 10, 11 and 12 are dropped by default. If the index carries information, move it into a column first with pdf.reset_index(). Otherwise to_pandas() returns a default RangeIndex starting at 0.
What changes in the conversion
Two details cause most surprises.
- Missing values. In a float column,
from_pandasconverts pandasNaNto Polarsnullby default (thenan_to_nullparameter isTrue). Converting back givesNaNin float columns again. Check the earlier chapter on null versus NaN if your logic depends on the difference. - Object columns. A pandas column with dtype
objectis inferred by Polars. Mixed types can raise an error. Cast the column in pandas first, for example withastype("string"), before converting.
Choosing where to convert
Place conversions at the edges of a module, so the inside works in one library only.
A wrapper function keeps the boundary in one place:
import pandas as pd
import polars as pl
def add_total(pdf: pd.DataFrame) -> pd.DataFrame:
df = pl.from_pandas(pdf)
out = df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
return out.to_pandas()
orders = pd.DataFrame({"price": [10.0, 20.0], "qty": [3, 5]})
print(add_total(orders))Callers still pass and receive pandas, so you can replace the internals without touching them. Later you remove the wrapper once the callers are migrated too.
Exercise
A pandas DataFrame has a custom index of customer IDs. You convert it with pl.from_pandas(pdf) and the IDs are gone. What should you have done, and what does to_pandas() return as the index?
Show answer
Call pdf.reset_index() before converting, so the IDs become a regular column. Polars has no index, so to_pandas() returns a default RangeIndex starting at 0. You can restore the old index afterward with set_index("customer_id").