Sub topic 6
Why assign takes lambdas: referring to the current state
This chapter assumes you can write basic Python functions and lambdas, build a DataFrame, filter rows, and have used assign to add a column. It explains why the value you give assign is usually a lambda, and what goes wrong without one.
The problem: the intermediate frame has no name
In a chain, each step produces a new DataFrame that you never assign to a variable. Inside assign, you still need a way to refer to that frame. Naming df does not work, because df is the original frame from before the chain started.
Here is a chain that silently gives wrong numbers:
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],
})
wrong = (
df
.query("quantity > 1")
.reset_index(drop=True)
.assign(revenue=df["price"] * df["quantity"])
)
print(wrong["revenue"].tolist())This prints [20.0, 20.0, 45.0]. The correct revenues for orders 1, 3 and 4 are 20, 45 and 50.
df["price"] * df["quantity"] is evaluated before the chain runs, on the original four rows. assign then aligns that Series with the filtered frame by index label. After reset_index, label 1 refers to order 3 in the filtered frame but to order 2 in df. No error is raised.
The fix: pass a callable
assign accepts a function in place of a value. When it sees a callable, it calls it with the current DataFrame and uses the return value as the new column.
right = (
df
.query("quantity > 1")
.reset_index(drop=True)
.assign(revenue=lambda d: d["price"] * d["quantity"])
)
print(right["revenue"].tolist())This prints [20.0, 45.0, 50.0]. The lambda's parameter d is the frame as it exists at that point in the chain: filtered, with the new index.
What the lambda receives
- It is called once per keyword argument, not once per row.
dis the whole DataFrame, so write vectorized expressions such asd["price"] * d["quantity"], not row-by-row logic. - It receives a frame that already includes any columns created by earlier steps in the chain.
- It must return something
assigncan turn into a column: a Series with a matching index, an array of the right length, or a scalar.
Non-callable values still work when they do not depend on the frame. A constant is fine:
tagged = df.assign(source="web")Use a callable whenever the value is computed from the frame's own columns.
Lambda or named function
The name d is a convention, not a requirement. For a short expression, a lambda is clear. For anything longer, define a function and pass it by name. assign calls it the same way:
def revenue(frame):
return frame["price"] * frame["quantity"]
result = df.query("quantity > 1").assign(revenue=revenue)Pass revenue, not revenue(df). Adding the parentheses calls the function immediately on the original frame, which brings back the problem above.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Wrong values, no error, after a filter or sort | The expression uses `df[...]` instead of the intermediate frame | Use `lambda d: d[...]` |
| `TypeError: 'Series' object is not callable` or similar | A function was called with `()` before being passed | Pass the function object without parentheses |
| `KeyError` on a column | The lambda refers to a column that does not exist yet at this step | Check the order of steps, or create it in an earlier `assign` |
| `ValueError` about length | The lambda returned a list or array of the wrong length | Return a Series built from `d`, or an array with `len(d)` items |
Exercise
The chain below runs without error but gives wrong results. Explain why, and rewrite the last step. result = ( df .sort_values("price") .assign(total=df["price"] * df["quantity"]) )
Show answer
df["price"] df["quantity"] is computed on the original frame before sorting. assign aligns it to the sorted frame by index label. Sorting keeps the original labels, so alignment happens to give each row its own total and the result is correct here. If the chain contains reset_index(drop=True) after sorting, alignment pairs the wrong rows. To make the step independent of the chain order, write .assign(total=lambda d: d["price"] d["quantity"]).