Sub topic 1
Why and When to Migrate from pandas to Polars
Prerequisites
This chapter assumes working knowledge of pandas, Python method chaining, and common numeric, string, and datetime types.
Why and When to Migrate from pandas to Polars
Polars is a DataFrame library designed for fast, parallel processing. Consider it when pandas code is slow, data is larger than memory-friendly workflows, or you want query optimization through the lazy API.
Pandas remains a good choice for small datasets, established integrations, and code that depends on pandas-specific extensions. Migration also has a learning cost. Measure a representative workload before changing libraries.
The Polars Mental Model: No Index, Immutable Frames, Expressions
Polars has no pandas-style index. Rows are identified by their position unless you create an ordinary column for an ID. DataFrames are immutable: methods return new frames instead of changing the original in place.
Polars operations use expressions. An expression describes a computation, such as pl.col("price") * pl.col("qty"). A context, such as select, filter, or with_columns, determines how Polars evaluates that expression.
Reading, Writing, and Inspecting Data
Use read_csv, read_parquet, and matching write methods. Inspect shape, column names, and schema before translating complex logic.
import polars as pl
df = pl.read_csv("orders.csv")
print(df.head())
print(df.shape)
print(df.schema)
result = (
df.with_columns(
(pl.col("price") * pl.col("qty")).alias("total")
)
.filter(pl.col("total") > 100)
.select("order_id", "region", "total")
.sort("total", descending=True)
)
result.write_parquet("large-orders.parquet")Dtypes and Schemas
A schema maps each column name to its Polars data type. Polars distinguishes signed and unsigned integers, floating-point values, strings, dates, datetimes, and null values. Check inferred types because CSV inference can differ from pandas expectations. Supply dtypes when reliable input types matter.
Expressions and Common Contexts
| Context | Purpose |
|---|---|
| `select` | Choose or compute columns |
| `with_columns` | Add or replace columns |
| `filter` | Keep rows matching an expression |
| `group_by().agg()` | Reduce rows into groups |
Pandas assignment and boolean masks therefore become expression pipelines. agg receives expressions such as pl.col("total").sum().alias("revenue").
Selecting, Filtering, and Sorting
Use column names or pl.col to select data, combine conditions with & and |, and sort with sort. Parenthesize each condition. Unlike pandas, filter does not take a boolean Series indexed against the frame.
Exercise
Why does Polars return a new DataFrame after with_columns?
Show answer
Polars DataFrames are immutable, so the method returns a transformed frame rather than modifying the original.