Sub topic 3
Migrating pandas Code to Polars: Strings, Datetimes, and Migration
Assume you know pandas method chaining, lambdas, common dtypes, and package installation. Polars uses expressions instead of row-by-row operations, so many pandas patterns need a different shape.
String and datetime namespaces
Polars groups type-specific operations in namespaces. Use .str for strings and .dt for dates and times.
import polars as pl
df = pl.DataFrame({
"name": [" Ada ", "Grace Hopper"],
"stamp": ["2026-01-03", "2026-02-10"],
})
result = df.with_columns(
pl.col("name").str.strip_chars().str.to_uppercase().alias("name_clean"),
pl.col("stamp").str.to_date("%Y-%m-%d").alias("date"),
).with_columns(
pl.col("date").dt.month().alias("month")
)Unlike pandas, a datetime expression does not modify the frame in place.
Reshaping with pivot and unpivot
Use pivot to turn category values into columns. Use unpivot to turn several columns into rows.
wide = pl.DataFrame({
"id": [1, 1, 2],
"metric": ["sales", "cost", "sales"],
"value": [10, 4, 8],
}).pivot(on="metric", index="id", values="value")
long = wide.unpivot(
on=["sales", "cost"],
index="id",
variable_name="metric",
value_name="value",
)The lazy API and query optimization
scan_csv creates a LazyFrame. Polars delays execution until collect(), then can push filters and column selection toward the file read.
result = (
pl.scan_csv("orders.csv")
.filter(pl.col("qty") > 0)
.select(["region", "price", "qty"])
.with_columns((pl.col("price") * pl.col("qty")).alias("revenue"))
.collect()
)Replace apply and row iteration
Prefer column expressions, when, and over over apply, iterrows, or explicit loops. Use map_elements only when the logic truly cannot be expressed with built-in expressions.
Convert and migrate incrementally
Keep pandas at system boundaries:
polars_df = pl.from_pandas(pandas_df)
pandas_df = polars_df.to_pandas()Migrate one pipeline or function at a time. Preserve the old pandas result while replacing one transformation, then compare outputs before continuing.
> callout note > Normalize column names, row order, dtypes, and missing-value rules before comparing results.
Validate migrated results
Use Polars testing helpers. Reset pandas indexes before conversion because Polars has no index.
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)Exercise
Why should collect() appear at the end of a lazy Polars pipeline?
Show answer
It triggers execution after Polars has had a chance to optimize the complete query.