Sub topic 7
Creating and modifying columns
This chapter assumes you have read the earlier chapters on expressions and on selecting and filtering. You should know that pl.col("x") builds an expression and that a frame is never changed in place.
Why assignment looks different
In pandas you write pdf["total"] = ... and the frame changes. Polars has no in-place column assignment. df["total"] = ... raises a TypeError. You call with_columns, which returns a new DataFrame. You then bind that result to a name.
with_columns handles two cases with one syntax. If the output name is new, it adds a column. If the name already exists, it replaces that column.
import polars as pl
df = pl.DataFrame({
"price": [10.0, 40.0, 80.0],
"qty": [2, 3, 1],
})
df = df.with_columns(
(pl.col("price") * pl.col("qty")).alias("total"), # new column
pl.col("qty").cast(pl.Float64), # replaces qty
)
print(df)An expression keeps the name of the first column it uses. Without .alias("total"), the product above would overwrite price. Add alias whenever you want a new column.
Conditional values
np.where and df.loc[mask, "col"] = value both become when/then/otherwise. Wrap plain values in pl.lit so Polars treats them as values, not column names.
df = df.with_columns(
pl.when(pl.col("total") > 100)
.then(pl.lit("large"))
.when(pl.col("total") > 30)
.then(pl.lit("medium"))
.otherwise(pl.lit("small"))
.alias("size")
)Chain extra when branches in place of nested np.where calls. If you leave out otherwise, rows that match no branch become null.
Modifying many columns at once
Selectors and name helpers replace loops over column names:
df = df.with_columns(
pl.col("price", "total").round(1).name.suffix("_rounded")
)Without name.suffix, the same expression would overwrite price and total.
Dependencies within one call
df = (
df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
.with_columns((pl.col("total") * 0.2).alias("tax"))
)pandas migrants often hit this error because sequential assignment worked there. A chain of with_columns calls is the Polars equivalent.
Other common translations
| pandas | Polars |
|---|---|
| `pdf["a"] = 0` | `df.with_columns(a=pl.lit(0))` |
| `pdf["a"].astype("float")` | `pl.col("a").cast(pl.Float64)` |
| `pdf.rename(columns={"a": "b"})` | `df.rename({"a": "b"})` |
| `pdf.drop(columns=["a"])` | `df.drop("a")` |
| `pdf.assign(b=...)` | `df.with_columns(b=...)` |
Keyword arguments such as with_columns(a=...) name the column for you, so no alias is needed. Use df.with_row_index("id") when you need a row counter, since there is no index to read it from.
Exercise
A learner writes df.with_columns(pl.col("price") * 2) and finds that price was overwritten instead of a new column being added. What is the cause, and how do they fix it?
Show answer
An expression keeps the name of the column it starts from, so the result is named price and replaces the original. Fix it by adding an alias: df.with_columns((pl.col("price") * 2).alias("price_x2")), or by using a keyword argument: df.with_columns(price_x2=pl.col("price") * 2).