Sub topic 7
Creating and Modifying Columns
This chapter assumes you know pandas column assignment, np.where, and apply. It also assumes you have read the earlier chapters on expressions and on selecting and filtering. Here you will translate the most common pandas column operations into Polars with_columns, and learn the errors that appear during porting.
From assignment to with_columns
In pandas, you add or change a column by assigning to a key. This mutates the frame in place. Polars frames are immutable. with_columns returns a new DataFrame that contains the original columns plus the new or replaced ones.
import pandas as pd
import polars as pl
pdf = pd.DataFrame({"price": [10.0, 60.0, 25.0], "qty": [2, 3, 8]})
pdf["total"] = pdf["price"] * pdf["qty"]
df = pl.DataFrame({"price": [10.0, 60.0, 25.0], "qty": [2, 3, 8]})
df = df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
print(df)Two details matter here:
- You must rebind the result (
df = df.with_columns(...)). Callingdf.with_columns(...)alone does nothing visible, because the originaldfis unchanged. - The new column needs a name. If you do not call
alias, the result takes the name of the first column in the expression, which here would overwriteprice. This is a common source of silent bugs.
You can also name columns with keyword arguments, which avoids alias:
df = df.with_columns(total=pl.col("price") * pl.col("qty"))Replacing and overwriting columns
If the output name matches an existing column, Polars replaces that column in place within the new frame. Column order is kept.
df = df.with_columns(pl.col("price").round(0))This replaces price and keeps its position. A new name is appended at the end.
Parallel evaluation inside one call
All expressions in a single with_columns call are evaluated against the same input frame, and they run in parallel. They cannot see each other's results. This differs from a sequence of pandas assignments, where each line sees the previous one.
# Fails: "tax" does not exist yet when "gross" is computed
df.with_columns(
tax=pl.col("total") * 0.2,
gross=pl.col("total") + pl.col("tax"),
)This raises a ColumnNotFoundError. There are two fixes. You can chain two calls, or you can repeat the expression:
df = (
df.with_columns(tax=pl.col("total") * 0.2)
.with_columns(gross=pl.col("total") + pl.col("tax"))
)Constants and literals
In pandas, pdf["source"] = "web" broadcasts a scalar. In Polars, a bare string inside an expression is read as a column name, so you must mark constants with pl.lit.
df = df.with_columns(
source=pl.lit("web"),
discount=pl.lit(0.1),
)Note the difference between pl.col("web") and pl.lit("web"). Some methods, such as pl.col, select, and group_by, treat plain strings as column names. Others treat them as values. When a string is meant as a value inside an expression, use pl.lit to be explicit.
Conditional columns: when, then, otherwise
np.where and boolean-mask assignment become pl.when(...).then(...).otherwise(...). Chain further when calls to replace nested np.where or np.select.
df = df.with_columns(
size=pl.when(pl.col("total") > 100)
.then(pl.lit("large"))
.when(pl.col("total") > 40)
.then(pl.lit("medium"))
.otherwise(pl.lit("small"))
)Branches are tested in order, and the first true condition wins. If you leave out otherwise, rows that match no branch become null. In pandas, np.where forces you to give both outcomes, so this is a new way to produce nulls by accident.
A mask assignment such as pdf.loc[pdf["qty"] > 5, "price"] = 0 has no direct equivalent, because Polars does not assign into a slice. Rewrite it as a replacement of the whole column:
df = df.with_columns(
price=pl.when(pl.col("qty") > 5).then(0.0).otherwise(pl.col("price"))
)Here the otherwise branch keeps the original values. This is the standard pattern for "update some rows."
Per-group values with over
groupby().transform() becomes .over(). The expression is computed per group and returned for every row, so the frame keeps its length.
df = df.with_columns(
region_mean=pl.col("total").mean().over("region"),
)The next chapters on grouping and windows cover over in detail. For this chapter, remember that it is a column-creating tool and belongs inside with_columns.
Casting and type changes
astype becomes cast. Casting is strict by default. If a value cannot be converted, Polars raises an error instead of quietly producing a wrong value.
df = df.with_columns(
pl.col("qty").cast(pl.Float64),
pl.col("price").cast(pl.Int64, strict=False),
)With strict=False, values that cannot be converted become null. Use this on purpose, for example when parsing messy input, and check the null count afterward. Casting a float with a fractional part to an integer drops the fraction.
Renaming, dropping, and reordering
These operations also return new frames.
| pandas | Polars |
|---|---|
| `pdf.rename(columns={"a": "b"})` | `df.rename({"a": "b"})` |
| `pdf.drop(columns=["a"])` | `df.drop("a")` |
| `pdf.assign(c=...)` | `df.with_columns(c=...)` |
| `pdf[["b", "a"]]` | `df.select("b", "a")` |
| `pdf.insert(0, "c", ...)` | `df.select(c_expr.alias("c"), pl.all())` |
Polars has no insert-at-position method. To put a new column first, build it in select and then add pl.all(). Be careful: if the new column has the same name as an existing one, you will get a duplicate-name error, so drop the old column first.
Applying one expression to many columns
Use pl.col with several names, a list, a dtype, or a selector to apply one operation to many columns. Each result keeps its source column name.
df = df.with_columns(pl.col("price", "total").round(2))
df = df.with_columns(pl.col(pl.Float64).fill_null(0.0))To derive new columns from many sources, use name.suffix or name.prefix:
df = df.with_columns((pl.col("price", "total") * 1.2).name.suffix("_gross"))This replaces a pandas loop over a list of column names.
Common errors when porting
| Symptom | Cause | Fix |
|---|---|---|
| `ColumnNotFoundError` for a column you just made | Expressions in one call do not see each other | Chain another `with_columns` |
| Column is silently overwritten | Missing `alias` on an expression whose root is that column | Name the result with `alias` or a keyword |
| Strings treated as column names | Constant not wrapped in `pl.lit` | Use `pl.lit("text")` |
| Unexpected nulls in a new column | `when/then` without `otherwise` | Add an `otherwise` branch |
| `InvalidOperationError` on cast | Strict cast hit an unconvertible value | Fix the data, or use `strict=False` and check nulls |
| `df["a"] = ...` raises an error | Polars frames do not support item assignment | Use `with_columns` |
Overview of the flow
Exercise
This pandas code assigns a discount and then a final price that depends on it. Rewrite it in Polars so it runs without error. Also, rows with qty of 0 must get a final of 0.0.
pdf["discount"] = np.where(pdf["qty"] >= 10, 0.2, 0.0)
pdf["final"] = pdf["price"] pdf["qty"] (1 - pdf["discount"])
Show answer
The second column reads the first, so the steps need two with_columns calls. The zero-quantity case follows from the arithmetic, but when/then/otherwise makes the rule explicit.
df = (
df.withcolumns(
discount=pl.when(pl.col("qty") >= 10).then(0.2).otherwise(0.0)
)
.withcolumns(
final=pl.when(pl.col("qty") == 0)
.then(0.0)
.otherwise(pl.col("price") pl.col("qty") (1 - pl.col("discount")))
)
)
Exercise
What does df.with_columns(pl.col("price") * 2) do to the frame, and what does it return?
Show answer
It returns a new frame in which the existing price column is replaced by the doubled values, because the expression keeps the name of its root column. The original df is unchanged unless you assign the result back.