Sub topic 4
Contexts: select, with_columns and filter
This chapter assumes you can build a DataFrame and write a basic pl.col(...) expression, as covered in the previous chapters. It also assumes you know Python method chaining. It explains what a context is, how the three most common contexts differ, and which errors you will hit if you treat them like pandas operations.
Expressions need a context
An expression such as pl.col("salary") * 1.1 is a description of a computation. It does not hold data and it does nothing on its own. A context is a DataFrame method that receives expressions, evaluates them against the frame, and builds a result from the output.
The context decides what happens to the results:
| Context | Existing columns | Rows | Typical use |
|---|---|---|---|
| `select` | Dropped unless you select them again | Same count, or one row if everything is an aggregate | Choose or compute the columns you want |
| `with_columns` | Kept, unless an output has the same name | Same count | Add or replace columns |
| `filter` | Kept | Only rows where the predicate is true | Keep a subset of rows |
| `group_by(...).agg(...)` | Replaced by keys and aggregates | One row per group | Covered in a later chapter |
The same expression can be passed to different contexts and gives different frames.
select: build a new frame
select returns only what its expressions produce. Use it when you want a specific set of columns.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
out = df.select(
pl.col("name"),
(pl.col("salary") * 1.1).alias("raised"),
)
print(out.shape) # (4, 2): dept and salary are gone
print(out.columns) # ['name', 'raised']A few details about how select treats its arguments:
- A plain string is interpreted as a column name.
df.select("name", "salary")works and is shorthand forpl.col. - To get a constant, use
pl.lit.df.select("hello")looks for a column calledhelloand fails.df.select(pl.lit("hello"))creates a column of that text. - Keyword arguments name the output:
df.select(raised=pl.col("salary") * 1.1)is the same as using.alias("raised"). - Every output column needs a unique name.
df.select(pl.col("salary"), pl.col("salary") * 2)fails with aDuplicateError, because both results are calledsalary. Add.alias(...)to one of them.
Lengths and broadcasting
All outputs in one select must have the same length, with one exception. A result of length 1 is broadcast to match the others. Aggregations and literals both produce length 1, so this works:
print(
df.select(
pl.col("name"),
pl.col("salary").mean().alias("avg_salary"),
pl.lit("2026").alias("year"),
)
)Each row shows the same avg_salary and year. Two columns of different lengths greater than 1 do not broadcast. df.select(pl.col("name"), pl.col("salary").head(2)) raises a ShapeError, because one result has 4 rows and the other has 2.
If every expression is an aggregate, the output has one row. df.select(pl.col("salary").sum()) returns a 1-row frame.
with_columns: add or replace columns
with_columns has the same signature as select, but it starts from the full input frame. New names are appended. Names that already exist are overwritten in place, keeping their position.
result = (
df.with_columns(
(pl.col("salary") / 12).alias("monthly"),
pl.col("name").str.to_uppercase(),
)
.filter(pl.col("salary") >= 90)
)
print(result)The second expression has no .alias, so its output name is the input name, name. That replaces the existing column. This is the usual way to update a column in Polars. Polars returns a new DataFrame and leaves df unchanged, so no in-place assignment exists.
Expressions in one call do not see each other
All expressions passed to one context are evaluated against the same input frame, and Polars may run them in parallel. An expression cannot use a column that another expression in the same call creates.
try:
df.with_columns(
(pl.col("salary") / 12).alias("monthly"),
(pl.col("monthly") * 3).alias("quarterly"),
)
except pl.exceptions.ColumnNotFoundError as err:
print("fails:", type(err).__name__)
# Fix 1: chain two calls so the second sees the first's output
fixed = (
df.with_columns((pl.col("salary") / 12).alias("monthly"))
.with_columns((pl.col("monthly") * 3).alias("quarterly"))
)
# Fix 2: repeat the computation in one call
fixed2 = df.with_columns(
(pl.col("salary") / 12).alias("monthly"),
(pl.col("salary") / 12 * 3).alias("quarterly"),
)
print(fixed.columns, fixed2.columns)Prefer the single call when the expressions are independent, because Polars can run them in parallel. Use a chain only when a later step needs an earlier result.
filter: keep rows by a boolean expression
filter takes an expression that evaluates to a boolean column and keeps the rows where it is true.
print(df.filter(pl.col("dept") == "eng"))
# Several predicates passed as separate arguments are combined with AND
print(df.filter(pl.col("dept") == "ops", pl.col("salary") > 80))
# Combine conditions in one expression with & (and), | (or), ~ (not)
print(df.filter((pl.col("salary") > 85) & (pl.col("dept") != "eng")))Two errors come up often here.
- Using
and/or. Python'sandneeds a plain True or False, and an expression has no truth value yet. It raises an error saying the truth value of an Expr is ambiguous. Use&,|and~. - Missing parentheses. In Python,
&binds more tightly than>or==. Writingpl.col("a") > 1 & pl.col("b") < 5is parsed in a way that fails or gives the wrong result. Wrap each comparison in parentheses.
Nulls are dropped
A predicate that evaluates to null is not true, so filter removes that row. This surprises people when they filter with "not equal".
data = pl.DataFrame({"x": [1, None, 3]})
print(data.filter(pl.col("x") != 1)) # only the row with 3The row with the null is removed too, because null != 1 is null, not true. To keep it, say so: data.filter((pl.col("x") != 1) | pl.col("x").is_null()). Null handling gets its own chapter.
Choosing the right context
Ask what shape you want back.
- Only certain columns, possibly computed:
select. - Everything you have, plus or modified columns:
with_columns. - Fewer rows:
filter. - One row per group:
group_by(...).agg(...).
A common mistake from pandas is to reach for select when updating one column. It works, but you silently lose every column you did not list. If your intent is "add" or "change", use with_columns.
Expressions that expand to many columns
A single expression can produce several outputs. pl.col("salary", "name") and pl.all() expand to one output per matching column, and the context handles each one. Expansion is also why pl.all() * 2 inside with_columns can fail on string columns. The multiplication is attempted on every column, and the string columns do not support it. A later chapter covers selectors, which let you pick columns by type or pattern instead.
Exercise
Using the DataFrame df from this chapter (columns name, dept, salary), write one chain that keeps only the rows with salary above 85, adds a monthly column equal to salary divided by 12, and then adds a yearlycheck column equal to monthly times 12. Which contexts do you use, and why can't monthly and yearlycheck be created in the same with_columns call?
Show answer
Use filter(pl.col("salary") > 85), then withcolumns for monthly, then a second withcolumns for yearlycheck: df.filter(pl.col("salary") > 85).withcolumns((pl.col("salary") / 12).alias("monthly")).withcolumns((pl.col("monthly") * 12).alias("yearlycheck")). Expressions in one withcolumns call are all evaluated against the same input frame, so monthly does not exist yet when yearlycheck is computed and a ColumnNotFoundError is raised. Either chain two calls, or write yearly_check as pl.col("salary") / 12 * 12 in the same call.
Exercise
What does df.filter(pl.col("x") != 1) do with rows where x is null, and how would you keep those rows?
Show answer
It removes them, because comparing null with 1 gives null, and filter keeps only rows where the predicate is true. To keep them, combine the comparison with a null check: df.filter((pl.col("x") != 1) | pl.col("x").is_null()).