Sub topic 4
Contexts: select, with_columns and filter
This chapter assumes you can create a DataFrame and write simple expressions with pl.col, as covered in the earlier chapters. It also assumes basic Python method chaining.
Expressions need a context
An expression such as pl.col("salary") * 1.1 only describes a computation. It does nothing until you pass it to a context. A context is a DataFrame method that supplies the data, runs the expressions, and decides what shape the result has. The three contexts here differ in what they return.
| Context | Result columns | Result rows |
|---|---|---|
| `select` | Only the expressions you pass | Usually the same count (or one row per aggregate) |
| `with_columns` | All existing columns plus or replacing the new ones | Same count |
| `filter` | All existing columns | Only rows where the expression is true |
The three contexts in practice
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
selected = df.select(pl.col("name"), (pl.col("salary") * 1.1).alias("raised"))
extended = df.with_columns((pl.col("salary") / 12).alias("monthly"))
kept = df.filter((pl.col("salary") >= 90) & (pl.col("dept") == "eng"))
print(selected.shape) # (4, 2)
print(extended.shape) # (4, 4)
print(kept.shape) # (2, 3)select dropped dept and salary, because you did not list them. with_columns kept everything and appended monthly. If you give a new expression the name of an existing column, it replaces that column. filter kept Ana and Ben.
None of these methods modify df. Each returns a new DataFrame, so you chain them:
result = (
df.with_columns((pl.col("salary") / 12).alias("monthly"))
.filter(pl.col("salary") >= 90)
.select("name", "monthly")
)
print(result)Plain strings such as "name" work as shorthand for pl.col("name") in select.
Expressions in one context run in parallel
Polars evaluates all expressions in a single context call independently, and it may run them at the same time. So an expression cannot use a column that another expression in the same call creates.
# Fails with ColumnNotFoundError: "monthly" does not exist yet
# df.with_columns(
# (pl.col("salary") / 12).alias("monthly"),
# (pl.col("monthly") * 2).alias("double_monthly"),
# )
# Works: the second step sees the result of the first
ok = df.with_columns((pl.col("salary") / 12).alias("monthly")).with_columns(
(pl.col("monthly") * 2).alias("double_monthly")
)
print(ok.columns)Common errors
- Using
and,orornotin a filter. Python's keywords cannot combine expressions. Use&,|and~, and wrap each comparison in parentheses, because&binds more tightly than>=or==. - Expecting
selectto keep other columns. If columns vanish, you probably wantedwith_columns. - Assigning with
df["new"] = .... Polars DataFrames do not support item assignment. Usewith_columns. - Forgetting
alias. Without it, a result takes the name of the first column in the expression. Two unnamed results frompl.col("salary")then collide and raise a duplicate-name error.
Exercise
You run df.select((pl.col("salary") / 12).alias("monthly")) and the name and dept columns disappear. Which method should you use to keep them, and why?
Show answer
Use withcolumns. select returns only the expressions you pass to it, while withcolumns returns all existing columns plus the new or replaced ones.
Exercise
Why does df.filter(pl.col("salary") >= 90 and pl.col("dept") == "eng") fail, and how do you fix it?
Show answer
Python's and keyword tries to convert an expression to a single boolean, which Polars does not allow. Write df.filter((pl.col("salary") >= 90) & (pl.col("dept") == "eng")), using & and parentheses around each comparison.