Sub topic 2
The Polars mental model: no index, immutable frames, expressions
This chapter assumes you know pandas DataFrames and Series, basic Python including lambdas and method chaining, and common dtypes. It also assumes you can install packages with pip (pip install polars). Three ideas explain most of the differences you will meet when porting code.
No index
A pandas DataFrame carries an index, and many operations align on it. Polars has no index. Rows are identified by position only. This removes a class of bugs, such as misaligned assignment after a filter, but it changes some habits.
- There is no
reset_index(). Code that uses it can usually be deleted. - There is no
.locor.iloc. Usefilterfor conditions and slicing for positions. - A column that used to live in the index becomes a normal column.
- A group-by result has no index. The group keys are ordinary columns.
Immutable frames
Polars does not modify a frame in place. Methods such as with_columns and filter return a new DataFrame, and the original stays unchanged. Assigning with df["total"] = ... is not the idiomatic style. Chain methods and bind the result to a name.
Expressions
An expression describes a computation on columns. It does not run until a context (a method such as select, with_columns, filter or agg) evaluates it. pl.col("price") refers to a column. Operators and methods on it build a larger expression.
The same logic in both libraries:
import pandas as pd
import polars as pl
# pandas
pdf = pd.read_csv("orders.csv")
pdf["total"] = pdf["price"] * pdf["qty"]
large = pdf[pdf["total"] > 100]
# Polars
df = pl.read_csv("orders.csv")
large = (
df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
.filter(pl.col("total") > 100)
)In pandas, pdf["price"] is a concrete Series, and the boolean mask is indexed from the frame. In Polars, pl.col("total") > 100 is an expression that filter applies to the frame it is called on. You never write the frame's name inside the condition.
Common errors
- Expecting in-place change. Calling
df.with_columns(...)without using the result does nothing visible. Assign it:df = df.with_columns(...). - Indexing with a mask.
df[df["total"] > 100]is the pandas habit. Usedf.filter(pl.col("total") > 100). - Forgetting
alias. A computed expression is named after its first column. Withoutalias,price * qtyis calledprice, and it can silently replace the original column inwith_columns.
Exercise
A colleague writes df.with_columns((pl.col("price") * pl.col("qty")).alias("total")) on its own line, then prints df.columns and does not see total. Why, and what is the fix?
Show answer
Polars frames are immutable, so with_columns returns a new DataFrame and leaves df unchanged. The fix is to bind the result: df = df.with_columns(...).