Sub topic 4
Chaining column creation with assign()
This chapter assumes you can build a DataFrame, select a column by name, and read a lambda expression. It also assumes you know that df["col"] = ... adds a column. Here you will learn how assign() does the same job inside a method chain, how its evaluation order works, and where it goes wrong.
Why assign() exists
Direct assignment changes the DataFrame in place. That is fine in a script, but it breaks a chain of method calls, because assignment is a statement and does not return a value. assign() is a method that returns a new DataFrame with the extra columns. The original is left alone.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
with_total = df.assign(total=df["price"] * df["qty"])
print(df.columns.tolist())
print(with_total.columns.tolist())The first print shows ['item', 'price', 'qty']. The second shows ['item', 'price', 'qty', 'total']. The input frame is unchanged.
Passing values and passing callables
Each keyword argument to assign() becomes a column name. The value can be one of two kinds:
- A Series, array, list, or scalar. pandas uses it as is. A Series is aligned on the index, and a scalar is broadcast to every row.
- A callable, usually a lambda. pandas calls it with the DataFrame and uses the return value.
The callable form matters when you chain methods. Look at this chain:
result = (
df
.query("qty > 2")
.assign(total=df["price"] * df["qty"])
)
print(result)This runs, but it is subtly wrong. The expression df["price"] * df["qty"] is evaluated against the original df, before query() filters anything. It produces a Series for all three rows. pandas then aligns it on the index, so the filtered rows pick up the right values. The result happens to be correct only because the index survived the filter. If you had reset the index in between, the values would be misaligned.
Use a lambda to avoid this:
result = (
df
.query("qty > 2")
.assign(total=lambda d: d["price"] * d["qty"])
)
print(result)The lambda receives the frame as it exists at that point in the chain, which is the filtered one. The rule is simple: inside a chain, refer to the intermediate frame through a lambda, not through the original variable name.
Later columns can use earlier ones
Since pandas 0.23, keyword arguments are evaluated in the order you write them. A callable can therefore read a column created by an earlier argument in the same call.
df = df.assign(
total=lambda d: d["price"] * d["qty"],
total_with_tax=lambda d: d["total"] * 1.2,
)
print(df)Here total_with_tax reads total, which was added one step earlier. The lambda for each argument receives the frame as built so far.
This only works with callables. A plain value is computed before assign() runs, so it cannot see columns that assign() creates.
# Fails with KeyError: 'total' does not exist yet when the expression runs
# df.assign(total=df["price"] * df["qty"], with_tax=df["total"] * 1.2)The diagram shows how the frame grows from one argument to the next.
Column names that are not valid keywords
Keyword arguments must be valid Python identifiers. A name with a space or a dash cannot be written as my col=.... Unpack a dictionary instead:
df2 = df.assign(**{"total (tax incl.)": lambda d: d["total"] * 1.2})
print(df2.columns.tolist())Dictionary unpacking also helps when you build column names in a loop. Python 3.6 and later keeps the dictionary order, so the evaluation order stays predictable.
Overwriting an existing column
If the keyword matches an existing column, assign() replaces it in the returned frame. This is a common way to clean a column in a chain.
people = pd.DataFrame({
"name": [" Ann Lee", "bob ray "],
"joined": ["2026-01-15", "2026-02-03"],
})
clean = (
people
.assign(
name=lambda d: d["name"].str.strip().str.title(),
joined=lambda d: pd.to_datetime(d["joined"]),
)
.assign(join_month=lambda d: d["joined"].dt.month)
)
print(clean.dtypes)The second assign() could be merged into the first. Splitting them is a style choice that makes each step easy to read. It costs one extra copy, which rarely matters.
assign() compared with direct assignment
| Aspect | `df["x"] = ...` | `df.assign(x=...)` |
|---|---|---|
| Modifies the original | Yes | No, returns a new frame |
| Works inside a chain | No | Yes |
| Several columns at once | One per statement | Many per call |
| Name with spaces | Yes | Needs `**{...}` |
| Memory cost | Low | Copies the frame |
| Position of new column | End | End |
The memory cost deserves a note. assign() makes a copy of the frame, so on a very large DataFrame, many separate assign() calls can use noticeably more memory and time than one call with several arguments. With Copy-on-Write enabled (the default in pandas 3.0), the copy is lazy and shares data until something is modified, so the cost is much smaller.
Common errors
- Referring to the original variable inside a chain. As shown above,
df["price"]ignores earlier steps. Uselambda d: d["price"]. - Reading a new column from a non-callable.
with_tax=df["total"] * 1.2fails or uses a stale column. Use a lambda. - Forgetting to keep the result.
df.assign(total=...)on its own line does nothing visible. Writedf = df.assign(...)or bind it to a new name. - Late-binding lambdas in a loop. A lambda that uses a loop variable sees the variable's final value, not the value when the lambda was written. Bind the value as a default argument.
The fourth error is worth seeing in code:
scaled = df[["price"]]
wrong = scaled.assign(**{
f"price_x{k}": (lambda d: d["price"] * k) for k in [2, 3]
})
right = scaled.assign(**{
f"price_x{k}": (lambda d, k=k: d["price"] * k) for k in [2, 3]
})
print(wrong.columns.tolist(), wrong["price_x2"].tolist())
print(right.columns.tolist(), right["price_x2"].tolist())In wrong, both lambdas see k == 3, so price_x2 holds the price times 3. In right, the default argument fixes k for each lambda, and price_x2 is correct.
When to prefer which form
Use direct assignment for short scripts and for exploratory work where you change one frame step by step. Use assign() when the transformation is a pipeline you want to read from top to bottom, when you must not modify the caller's frame (for example, inside a function that receives a DataFrame), or when you want to combine it with query(), pipe(), and rename().
Writing a function that takes a frame and returns a new one is a good fit for assign():
def add_totals(frame: pd.DataFrame) -> pd.DataFrame:
return frame.assign(
total=lambda d: d["price"] * d["qty"],
share=lambda d: d["total"] / d["total"].sum(),
)
print(add_totals(df[["item", "price", "qty"]]))The caller's frame is not touched, so the function has no side effects.
Exercise
Given df with columns "price" and "qty", this code raises a KeyError: df.assign(total=df["price"] df["qty"], with_tax=df["total"] 1.2). Explain why, and rewrite it so it works.
Show answer
Both expressions are ordinary values, so Python evaluates them before assign() is called. When df["total"] is read, the column does not exist yet. Use callables so each one runs inside assign() on the frame built so far: df.assign(total=lambda d: d["price"] d["qty"], with_tax=lambda d: d["total"] 1.2).
Exercise
In the chain df.query("qty > 2").assign(total=df["price"] df["qty"]), why is the lambda form lambda d: d["price"] d["qty"] safer, even when the output looks the same?
Show answer
Without the lambda, the multiplication uses the original df, not the filtered frame, and pandas then aligns the result on the index. That works only while the index labels still match. The lambda receives the frame at that step of the chain, so it always uses the filtered rows, even after an operation such as reset_index().