Sub topic 16
Converting between pandas and Polars
This chapter assumes you can write pandas code with DataFrames and Series, and that you know basic Python and pip. You should also have read the earlier chapters on the Polars mental model (no index, immutable frames, expressions). Here you will learn how to move data between the two libraries, what changes during the move, and where to put the conversion points in a codebase you are migrating one piece at a time.
Why conversion matters during a migration
Few teams rewrite everything in one go. Plotting code, scikit-learn pipelines, and internal helper functions often still expect pandas objects. Conversion functions let Polars and pandas coexist while you migrate. Each conversion has a cost and can change data, so the goal is to convert at a few well-chosen boundaries and not inside loops.
Install both libraries and PyArrow. PyArrow is a library that stores columnar data in memory in a standard layout. Polars needs it for to_pandas.
# pip install polars pandas pyarrow
import pandas as pd
import polars as pl
print(pd.__version__, pl.__version__)From pandas to Polars
Use pl.from_pandas to turn a pandas DataFrame or Series into a Polars object.
import pandas as pd
import polars as pl
pdf = pd.DataFrame(
{
"region": ["north", "south", "north"],
"price": [10.0, 20.0, 30.0],
"qty": [1, 2, 3],
},
index=[100, 101, 102],
)
df = pl.from_pandas(pdf)
print(df)
print(df.schema)Three things to know about this call:
- The index is dropped. Polars has no index, so the labels
100, 101, 102are not in the result. If the index carries information, such as a date or an ID, move it into a column first withreset_index(). - A pandas
objectcolumn holding strings becomes a PolarsStringcolumn. Anobjectcolumn holding mixed types can fail or become anObjectdtype, so clean those columns first. - NaN values in float columns are handled by the
nan_to_nullargument, which is described below.
Keeping the index
df = pl.from_pandas(pdf.reset_index(names="order_id"))
print(df.columns)If you have a MultiIndex, reset_index() turns every level into a column. Check the column names afterwards, because unnamed levels become level_0, level_1, and so on.
NaN versus null on the way in
pandas uses NaN for missing floats. Polars distinguishes a missing value (null) from the floating-point NaN. By default from_pandas keeps NaN as NaN in float columns, and converts the missing markers of nullable pandas dtypes (such as Int64 or string) to null. Pass nan_to_null=True to turn NaN into null as well.
import numpy as np
pdf = pd.DataFrame({"x": [1.0, np.nan, 3.0]})
keep_nan = pl.from_pandas(pdf)
as_null = pl.from_pandas(pdf, nan_to_null=True)
print(keep_nan.select(pl.col("x").is_nan().sum().alias("nan_count"), pl.col("x").null_count().alias("nulls")))
print(as_null.select(pl.col("x").is_nan().sum().alias("nan_count"), pl.col("x").null_count().alias("nulls")))In pandas code, "missing" almost always means NaN. In migrated code you usually want null, because fill_null, drop_nulls, and is_null operate on null only. Using nan_to_null=True at the boundary is the common choice for that reason.
From Polars to pandas
Use DataFrame.to_pandas(). It needs PyArrow installed.
pdf_again = df.to_pandas()
print(pdf_again.dtypes)
print(pdf_again.index)The result has a default RangeIndex. Any index you had before the first conversion is gone unless you kept it as a column. To restore it, call set_index.
restored = df.to_pandas().set_index("order_id")Dtype changes
| Polars dtype | Typical pandas result |
|---|---|
| `Int64` with no nulls | `int64` |
| `Int64` with nulls | `float64` with NaN, unless you ask for nullable dtypes |
| `Float64` | `float64` |
| `String` | `object` |
| `Boolean` with nulls | `object` |
| `Datetime` | `datetime64[us]` or similar |
| `Categorical` | `category` |
Two consequences follow. An integer column that contains nulls silently becomes floating point, which can break code that expects integers. And null becomes NaN, so a distinction you kept inside Polars disappears. If you want to preserve integer and boolean columns with missing values, convert with PyArrow-backed or nullable dtypes:
pdf_arrow = df.to_pandas(use_pyarrow_extension_array=True)
print(pdf_arrow.dtypes)This keeps the data in Arrow memory, avoids a copy for many types, and keeps nulls as <NA>. Not every downstream library accepts Arrow-backed pandas columns, so test with the code that consumes the result.
Series and single columns
Series convert the same way.
s = pl.from_pandas(pd.Series([1, 2, 3], name="n"))
back = s.to_pandas()You can also take one column out of a frame with df["price"] or df.get_column("price"), and use .to_numpy() when a library wants a NumPy array. Scikit-learn and Matplotlib typically accept NumPy arrays, so for those you may not need pandas at all.
X = df.select("price", "qty").to_numpy()What a conversion costs
Conversions are not always free. The table summarizes what to expect.
| Direction | Copy? | Notes |
|---|---|---|
| pandas to Polars with Arrow-backed columns | Often zero-copy | Fastest path |
| pandas to Polars with NumPy-backed numeric columns | Usually a copy | Data is moved into Arrow layout |
| pandas to Polars with `object` strings | Copy and parse | Slowest, as each Python string is converted |
| Polars to pandas with `use_pyarrow_extension_array=True` | Often zero-copy | Keeps Arrow memory |
| Polars to pandas, default | Copy | Strings become Python objects |
Do not convert inside a loop or per row. Convert once, work in one library, and convert back once.
Where to put the boundary
A practical pattern is to wrap each migrated function so its public signature stays the same.
import pandas as pd
import polars as pl
def revenue_by_region(pdf: pd.DataFrame) -> pd.DataFrame:
"""Same signature as the old pandas version."""
df = pl.from_pandas(pdf, nan_to_null=True)
out = (
df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
.group_by("region")
.agg(pl.col("total").sum().alias("revenue"))
.sort("revenue", descending=True)
)
return out.to_pandas()Callers do not change, and you can check the new function against the old one. Later, when the callers move to Polars, you delete the wrappers and pass Polars frames directly. The next chapter on incremental migration builds on this idea.
Common errors
ModuleNotFoundError: pyarrowwhen callingto_pandas. Install PyArrow withpip install pyarrow.- Lost index. After
from_pandas, the original index is gone. Callreset_index()before converting. - Integer columns turn into floats after
to_pandaswhen they contain nulls. Useuse_pyarrow_extension_array=Trueor fill the nulls first. - Unexpected NaN counts. If
is_nullfinds nothing after conversion, the missing values are probably NaN. Usenan_to_null=True. - Mixed-type
objectcolumns raise errors or becomeObjectdtype. Cast them in pandas first, for example withastype(str)orpd.to_numeric. - Row order after conversion back. Operations such as
group_bydo not guarantee a stable group order unless you passmaintain_order=True. Sort explicitly before comparing.
Summary of conversion calls
| Task | Call |
|---|---|
| pandas DataFrame to Polars | `pl.from_pandas(pdf)` |
| Treat NaN as null | `pl.from_pandas(pdf, nan_to_null=True)` |
| Keep the index | `pl.from_pandas(pdf.reset_index())` |
| Polars to pandas | `df.to_pandas()` |
| Keep nulls and integers | `df.to_pandas(use_pyarrow_extension_array=True)` |
| Polars to NumPy | `df.to_numpy()` |
| Series conversion | `pl.from_pandas(s)` and `s.to_pandas()` |
Exercise
A pandas DataFrame has an integer user_id index and a float column score with NaN for missing scores. You convert it with pl.from_pandas(pdf). List two problems you would meet, and give the corrected call.
Show answer
First, the index is dropped, so user_id is lost. Second, the NaN values stay as NaN, so is_null() and fill_null() do not see them. The corrected call is pl.from_pandas(pdf.reset_index(names="user_id"), nan_to_null=True).
Exercise
A Polars column age of dtype Int64 contains some nulls. After df.to_pandas() the column is float64. Why does this happen, and how can you keep it as an integer type with missing values?
Show answer
NumPy-backed pandas integer columns cannot hold missing values, so pandas stores the column as float64 and uses NaN for the nulls. Call df.to_pandas(use_pyarrow_extension_array=True) to get an Arrow-backed integer column that keeps nulls as <NA>.