Sub topic 6
Why assign takes lambdas: referring to the current state
This chapter explains why assign accepts callables, usually lambdas, and why a plain reference to a variable often gives wrong results in the middle of a chain. It assumes you can write basic Python functions and lambdas, build and inspect a DataFrame, and filter rows and select columns. It also assumes you have seen the idea of a chain: each method returns a new DataFrame that the next method works on.
The problem: which DataFrame does the expression see?
Every example in this chapter uses this DataFrame:
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3, 4],
"region": ["east", "west", "east", "west"],
"price": [10.0, 20.0, 15.0, 5.0],
"quantity": [2, 1, 3, 10],
})Suppose you want revenue for the west region only. The obvious approach is to filter, then add a column built from the columns you already know:
west = df.query("region == 'west'").assign(revenue=df["price"] * df["quantity"])
print(west["revenue"].tolist())This prints [20.0, 50.0], which is correct. It works by accident. Python evaluates df["price"] * df["quantity"] before assign runs, and the result is a Series indexed 0 to 3 that belongs to the original df. assign aligns that Series with the filtered frame on index labels, and labels 1 and 3 happen to exist in both.
Add one more step and the accident ends:
west = (
df
.query("region == 'west'")
.reset_index(drop=True)
.assign(revenue=df["price"] * df["quantity"])
)
print(west["revenue"].tolist())This prints [20.0, 20.0]. The filtered frame now has index labels 0 and 1, so alignment picks the first two revenues of the original df. That is order 1 and order 2, not order 2 and order 4. No error and no warning appear. The numbers are simply wrong.
The cause is that df names the original data, but at that point in the chain the data has been filtered and re-indexed. The expression needs to refer to the frame the chain has produced so far.
The fix: pass a callable
A callable is any object you can call like a function, such as a lambda or a named function. If you give assign a callable, it does not run it right away. When assign is ready to create the column, it calls your function with the DataFrame it is working on and uses the return value as the column.
west = (
df
.query("region == 'west'")
.reset_index(drop=True)
.assign(revenue=lambda d: d["price"] * d["quantity"])
)
print(west["revenue"].tolist())This prints [20.0, 50.0]. The lambda's parameter d is the filtered, re-indexed frame, so the product uses the right rows. The name d is a convention. You could write df, but that shadows the outer variable and makes the code harder to read.
What happens inside assign
The sequence below shows what happens when assign receives a callable.
Three facts follow from this:
assigncopies the frame before it adds anything. The DataFrame it received, including your originaldf, is never modified.- Your callable receives the copy, not the original. If the same
assigncall has earlier keyword arguments, their columns are already on the copy when a later callable runs. The next chapter builds on this. - The callable runs at the moment
assignneeds it, after every earlier step in the chain has finished. That timing is why it sees the current state.
Callable versus non-callable arguments
assign accepts both kinds of value, and they behave differently.
| Argument | Example | When it is evaluated | What it sees |
|---|---|---|---|
| Callable | `lambda d: d["price"] * 2` | Inside `assign`, with the frame as input | The current frame in the chain |
| Series or array | `df["price"] * 2` | Before `assign` is called | Whatever variable you named, often an older frame |
| Scalar | `0.2` | Before `assign` is called | Nothing; it is broadcast to every row |
A Series is aligned on index labels. A NumPy array or list is matched by position and must have the same length as the frame. A scalar fills the whole column. All three work, but only the callable form can depend on the intermediate result.
Use a non-callable when the value does not depend on the frame in the chain. A constant tax rate or a column from a separate lookup table are examples. Use a callable whenever the value is computed from the frame that is flowing through the chain.
Replacing a column: the stale reference
The same problem appears when you overwrite a column and then use it. assign replaces a column if the name already exists.
stale = (
df
.assign(price=df["price"] * 2)
.assign(revenue=df["price"] * df["quantity"])
)
print(stale["price"].tolist())
print(stale["revenue"].tolist())The output is:
[20.0, 40.0, 30.0, 10.0]
[20.0, 20.0, 45.0, 50.0]The price column is doubled, but revenue was computed from the original prices, because df in the second assign is still the original. With lambdas, each step reads the result of the step before it:
fresh = (
df
.assign(price=lambda d: d["price"] * 2)
.assign(revenue=lambda d: d["price"] * d["quantity"])
)
print(fresh["revenue"].tolist())This prints [40.0, 40.0, 90.0, 100.0], which is the doubled price times quantity.
Callables are used in other places too
The idea is not specific to assign. Several pandas accessors accept a callable that receives the current frame:
result = (
df
.loc[lambda d: d["quantity"] > 1]
.loc[:, lambda d: ["order_id", "price"]]
)
print(result).loc called the first lambda with df and used the returned boolean Series to select rows. It called the second with the filtered frame and used the returned list to select columns. Plain [] indexing also accepts a callable, as in df[lambda d: d["price"] > 10]. This is how you filter inside a chain on a column that an earlier step just created, without a temporary variable.
The return value rules
Your callable can return any of these:
- A Series. Aligned on the index of the current frame.
- A NumPy array, list or other sequence with the same length as the frame.
- A scalar, which is broadcast to all rows.
Returning a DataFrame fails, because a column holds one value per row. If you want to add several columns from a DataFrame result, add them with separate keyword arguments.
Alignment still applies to Series. If your callable builds a Series from some other frame, for example a lookup table with different index labels, the values are matched by label and unmatched rows get NaN. Computing from d itself avoids the issue, because the index is the same by construction.
A gotcha: lambdas that capture a loop variable
When you build the assign arguments in a loop or a comprehension, a lambda that refers to the loop variable can end up using the wrong value. Python looks up a captured variable when the lambda runs, not when it is defined.
cols = ["price", "quantity"]
bad = df.assign(**{f"{c}_x2": (lambda d: d[c] * 2) for c in cols})
print(bad["price_x2"].tolist())This prints [4, 2, 6, 20]. By the time assign calls the lambdas, the comprehension has finished and c holds its last value, "quantity". Both new columns are therefore built from quantity. The price_x2 column should be [20.0, 40.0, 30.0, 10.0].
There are two fixes. The first binds the current value as a default argument. assign only passes one argument, so the default is never overwritten:
good = df.assign(**{f"{c}_x2": (lambda d, c=c: d[c] * 2) for c in cols})
print(good["price_x2"].tolist())The second is to use a non-callable, which is evaluated immediately inside the comprehension:
good = df.assign(**{f"{c}_x2": df[c] * 2 for c in cols})The second form is fine here because both columns come from the unchanged df. If the values depended on an earlier step in the chain, you would need the first form.
Named functions instead of lambdas
A lambda is a short anonymous function. For a longer expression, a named function does the same job and is easier to read and test. Any function that takes a DataFrame and returns something column-shaped works:
def revenue(d):
return d["price"] * d["quantity"]
result = df.assign(revenue=revenue)Pass the function without parentheses. Writing revenue=revenue(df) calls it immediately on the original df, which brings back the stale reference problem.
Quick checklist
- If the value depends on the frame at this point in the chain, pass a callable.
- If the value is a constant or comes from an unrelated source, a plain value is fine.
- Do not write
df[...]insideassignin the middle of a chain unless you are sure the frame is unchanged. - When you build lambdas in a loop, bind the loop variable with a default argument.
- Pass a function by name, not by calling it.
Exercise
Predict the printed list, then say whether it is correct for "price after a 10% discount, times quantity". result = ( df .assign(price=lambda d: d["price"] 0.9) .assign(revenue=df["price"] df["quantity"]) ) print(result["revenue"].tolist()) How would you fix it?
Show answer
It prints [20.0, 20.0, 45.0, 50.0]. The second assign uses df["price"], which is the original undiscounted price, because it is evaluated before assign runs. The first assign did not change df. The fix is to pass a lambda: .assign(revenue=lambda d: d["price"] * d["quantity"]). The result is then approximately [18.0, 18.0, 40.5, 45.0], with small floating-point differences possible.
Exercise
What does this code return, and why? Rewrite it so each new column is built from its own source column. cols = ["orderid", "quantity"] out = df.assign(**{f"{c}plusone": (lambda d: d[c] + 1) for c in cols}) print(out["orderidplusone"].tolist())
Show answer
It prints [3, 2, 4, 11]. Python looks up c when the lambdas are called, after the comprehension has finished, so both lambdas use c = "quantity". The orderidplusone column holds quantity plus one. The fix is to bind the variable as a default argument: lambda d, c=c: d[c] + 1. A non-callable also works here because df does not change: {f"{c}plus_one": df[c] + 1 for c in cols}.