Sub topic 2
The Polars mental model: no index, immutable frames, expressions
This chapter assumes you can work with pandas DataFrames and Series, write basic Python including lambdas and method chaining, and install packages with pip. It covers the three ideas that make Polars code look different from pandas code. Later chapters build on them.
Why the model matters before the syntax
Most pandas-to-Polars translation errors are not typos. They come from carrying over a habit that has no equivalent. If you look for df.loc, df.index or df["a"] = ... in Polars, you will not find them. Learning the three ideas below first saves you from translating line by line and getting awkward code.
| Idea | pandas habit | Polars approach |
|---|---|---|
| No index | Rows are labeled, and operations align on labels | Rows are only positions. Join explicitly on columns |
| Immutable frames | `df["c"] = ...` changes the frame in place | Methods return a new frame. You rebind the name |
| Expressions | Operate on Series you pull out of the frame | Describe a computation with `pl.col(...)`. A context runs it |
Install Polars with pip install polars. The examples use a small frame that you can build in memory.
import polars as pl
df = pl.DataFrame(
{
"region": ["north", "south", "north", "east"],
"price": [10.0, 25.0, 40.0, 5.0],
"qty": [3, 2, 4, 10],
}
)
print(df)No index
A pandas DataFrame always carries an index. Many pandas idioms use it: loc selects by label, reset_index turns it back into a column, and arithmetic between two Series aligns on matching labels.
A Polars DataFrame has no index. Rows have a position and nothing else. This has practical consequences.
- There is no
reset_index(). After a group-by there is nothing to reset, because the group keys are already ordinary columns. - There is no
locoriloc. You select rows with a filter expression, or by position with slicing anddf[0]-style row access. - Operations never align on labels. Two columns combine element by element, by position. If you need label-based matching, you do a join.
- If you want a row number, you ask for one with
with_row_index.
numbered = df.with_row_index("row_nr")
print(numbered)If your pandas code stores meaningful data in the index, such as a date or an ID, move it into a regular column before you migrate that part. Then the data is visible in the code, and you refer to it by name.
Immutable frames
In pandas you often change a frame in place:
# pandas
pdf["total"] = pdf["price"] * pdf["qty"]Polars does not modify a frame in place. Each method returns a new DataFrame, and the original stays as it was. To keep the result, assign it to a name.
df2 = df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
print(df.columns) # ['region', 'price', 'qty']
print(df2.columns) # ['region', 'price', 'qty', 'total']A common mistake is to call a method and discard the result:
df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
print(df.columns) # still has no "total"This runs without error, but df is unchanged. Polars also rejects item assignment of the form df["total"] = ... for new columns in recent versions, so most such mistakes fail loudly. The silent one is the discarded result above.
Immutability has two benefits. Chains of calls are safe to reorder or reuse, because no step can change a frame that another step reads. It also removes the SettingWithCopyWarning family of problems, since there is no ambiguity about whether you changed a copy or a view.
Copying is cheap in practice. Polars stores columns in Arrow-style memory, and a new frame can share the columns it did not change.
Expressions
The central idea in Polars is the expression. An expression is a description of a computation on one or more columns. It does not hold data and it does not run by itself.
expr = pl.col("price") * pl.col("qty")
print(expr) # prints the description of the computation, not numberspl.col("price") means "the column named price, whichever frame this expression runs on". Operators and methods on it build a larger expression. Because an expression is only a description, you can store it in a variable, pass it to a function, and apply it to different frames.
A pandas Series operation acts on data you already extracted. pdf["price"] * pdf["qty"] multiplies two concrete Series right away. In Polars you build the expression first and hand it to a context, which runs it against a frame.
Contexts
A context is a method that receives expressions and decides what to do with the results. The main ones are:
| Context | What it does | Output rows |
|---|---|---|
| `select` | Returns only the columns the expressions produce | Same as input, or one if reduced |
| `with_columns` | Adds or replaces columns, keeps the rest | Same as input |
| `filter` | Keeps rows where a boolean expression is true | Fewer or equal |
| `group_by(...).agg` | Evaluates expressions once per group | One per group |
result = (
df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
.filter(pl.col("total") > 30)
.select("region", "total")
)
print(result)Each step takes a frame and returns a frame, so the chain reads from top to bottom. There are no temporary variables and no mask indexed from the frame, as in pdf[pdf["total"] > 30]. The filter refers to the column by name inside the expression.
The same expression works in more than one context, and the context sets the result shape. This is the main difference from pandas.
total = pl.col("price") * pl.col("qty")
print(df.select(total.sum().alias("grand_total")))
print(df.group_by("region").agg(total.sum().alias("region_total")))The first call reduces the whole column to one row. The second evaluates the same total per region. You did not rewrite the logic, you only changed the context.
Parallel evaluation
When you pass several expressions to one context, Polars sees them all together and can run them in parallel, because none can see the others' results.
out = df.with_columns(
(pl.col("price") * 2).alias("price_x2"),
(pl.col("qty") + 1).alias("qty_plus_1"),
)This has one consequence for porting. Expressions in the same with_columns call all read the original frame. An expression cannot use a column created by its sibling in the same call.
# Fails: "total" does not exist yet when the second expression is built
df.with_columns(
(pl.col("price") * pl.col("qty")).alias("total"),
(pl.col("total") * 1.2).alias("total_with_tax"),
)Split the work into two chained calls, because the second call sees the output of the first:
out = (
df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
.with_columns((pl.col("total") * 1.2).alias("total_with_tax"))
)How the three ideas fit together
The ideas support each other. With no index, there is no hidden state to align on. With immutable frames, each step is a pure function from frame to frame. With expressions, each step is a description that can be inspected before it runs. This is also why Polars can offer a lazy mode, which you meet in a later chapter: the whole chain is known before any data is touched.
Translating the habits
When you port a line of pandas, ask three questions.
- Does it use the index? If yes, make that data a column and use a join or a filter.
- Does it assign into an existing frame? If yes, use
with_columnsand rebind the result. - Does it extract a Series and compute on it? If yes, write an expression with
pl.coland pass it to a context.
# pandas
pdf = pdf.set_index("region")
pdf.loc["north", "qty"] = 0
# Polars: no index, so the condition is an expression
df = df.with_columns(
pl.when(pl.col("region") == "north")
.then(0)
.otherwise(pl.col("qty"))
.alias("qty")
)Exercise
A colleague ports pdf["total"] = pdf["price"] * pdf["qty"] to Polars as df.with_columns((pl.col("price") * pl.col("qty")).alias("total")) on its own line. Later code reads df["total"] and fails with a column-not-found error. What went wrong, and how do you fix it?
Show answer
Polars frames are immutable, so with_columns returned a new DataFrame that was discarded. The original df has no "total" column. Rebind the result: df = df.with_columns((pl.col("price") * pl.col("qty")).alias("total")).
Exercise
You write df.with_columns((pl.col("price") * pl.col("qty")).alias("total"), (pl.col("total") * 1.2).alias("total_with_tax")) and get an error that "total" is not found. Why, and what is the fix?
Show answer
Expressions in one context all read the input frame, so the second expression cannot see the "total" column made by the first. Split it into two chained with_columns calls so the second call receives the frame that already has "total".