Sub topic 7
Several dependent columns in one assign
This chapter assumes you can write Python lambdas, build and inspect a DataFrame, and use assign to add a single column. It also assumes you know that assign returns a new DataFrame. The chapter covers what happens when one assign call creates several columns and a later column needs an earlier one.
The problem: columns that build on each other
A derived column often depends on another derived column. In the order data, share is each order's revenue divided by total revenue, and revenue does not exist until you compute it.
Here is the data used throughout the chapter:
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],
})You could write two assign calls, one per column. That works, but it adds a step to the chain for each dependent column. Pandas lets you put both columns in one call:
result = (
df
.assign(
revenue=lambda d: d["price"] * d["quantity"],
share=lambda d: d["revenue"] / d["revenue"].sum(),
)
)
print(result)This prints:
order_id region price quantity revenue share
0 1 east 10.0 2 20.0 0.148148
1 2 west 20.0 1 20.0 0.148148
2 3 east 15.0 3 45.0 0.333333
3 4 west 5.0 10 50.0 0.370370The second lambda reads d["revenue"], a column that is not in df. It works because of how assign evaluates its arguments.
How assign evaluates keyword arguments in order
assign makes a copy of the DataFrame and then processes the keyword arguments one at a time, in the order you wrote them. For each argument it does this:
- If the value is callable, it calls the value with the working copy as the only argument.
- It stores the result as a column on the working copy.
- It moves on to the next keyword.
Because the working copy gains revenue before the share lambda runs, that lambda's d already has a revenue column. The d in the second lambda is not the DataFrame you passed in. It is the copy with the earlier columns added.
Python keeps keyword arguments in the order they appear in the call. Pandas relies on this ordering, which is why one assign can build dependent columns safely.
The original df is never modified. After the call above, df.columns still lists only the four original columns.
Order matters
If you swap the two keywords, share runs before revenue exists:
try:
df.assign(
share=lambda d: d["revenue"] / d["revenue"].sum(),
revenue=lambda d: d["price"] * d["quantity"],
)
except KeyError as err:
print("KeyError:", err)This prints KeyError: 'revenue'. The rule is simple: a column can only be used by keywords that come after the one that creates it.
Dependencies can go several levels deep. The next example computes tax from revenue and a total from both:
result = (
df
.assign(
revenue=lambda d: d["price"] * d["quantity"],
tax=lambda d: d["revenue"] * 0.2,
total=lambda d: d["revenue"] + d["tax"],
)
)Each line builds on a column made in the lines above it. Read it top to bottom and the dependencies are clear. If you can't read the keywords in an order where each one only needs earlier columns, the logic probably has a circular dependency, and you need to rethink it.
Why plain values are different from lambdas
You can pass a Series or a scalar to assign instead of a callable. A non-callable value is evaluated when you write the call, before assign runs. It cannot see columns created inside the same call.
try:
df.assign(
revenue=df["price"] * df["quantity"],
share=df["revenue"] / df["revenue"].sum(),
)
except KeyError as err:
print("KeyError:", err)This also prints KeyError: 'revenue'. Python evaluates df["revenue"] while building the argument list, and the original df has no such column. assign never gets to run.
Plain values have a second problem inside a chain. In a chain, the DataFrame at a given step is an intermediate result, and the name df still refers to the start of the chain. A plain df["price"] ignores any filtering or renaming done earlier in the chain:
result = (
df
.query("region == 'east'")
.assign(revenue=df["price"] * df["quantity"]) # uses all four rows
)Pandas aligns the full-length Series to the filtered index, so this may appear to work and then give subtly wrong results when the index no longer matches. With a lambda, d is the filtered frame:
result = (
df
.query("region == 'east'")
.assign(revenue=lambda d: d["price"] * d["quantity"])
)Make lambdas your default in chains. Use plain values only when the value does not depend on the current DataFrame, such as a constant.
Replacing a column and using the new version
assign also overwrites an existing column. A later keyword in the same call sees the replaced version, not the original:
result = (
df
.assign(
price=lambda d: d["price"] * 100, # dollars to cents
revenue=lambda d: d["price"] * d["quantity"],
)
)
print(result[["price", "quantity", "revenue"]])This prints:
price quantity revenue
0 1000.0 2 2000.0
1 2000.0 1 2000.0
2 1500.0 3 4500.0
3 500.0 10 5000.0The revenue is in cents because the price lambda ran first. This is useful, and it is also a source of mistakes. If you wanted revenue in dollars, put revenue before price, so it sees the original prices.
Column position follows a simple rule. A replaced column stays where it was. New columns are appended at the right, in the order of the keywords.
Building the keywords from a dictionary
When the column names are not valid Python identifiers, or when you build the transformations programmatically, unpack a dictionary with **:
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.assign(**{"unit price": lambda d: d["revenue"] / d["quantity"]})
)A dictionary keeps its insertion order, so unpacking it preserves the evaluation order and the same dependency rules apply. A dictionary with several entries behaves exactly like several keyword arguments in one call.
A late-binding trap with lambdas in loops
If you create lambdas in a loop, each lambda looks up the loop variable when it runs, not when it was defined. All of them then see the last value:
cols = {}
for factor in (1, 2, 3):
cols[f"price_x{factor}"] = lambda d: d["price"] * factor
wrong = df.assign(**cols)
print(wrong[["price_x1", "price_x2", "price_x3"]].head(1))The three columns come out identical, all multiplied by 3. Bind the current value with a default argument. assign calls each function with one argument, so the default is never overwritten:
cols = {}
for factor in (1, 2, 3):
cols[f"price_x{factor}"] = lambda d, f=factor: d["price"] * f
right = df.assign(**cols)
print(right[["price", "price_x1", "price_x2", "price_x3"]].head(1))The first row now shows 10.0, 10.0, 20.0 and 30.0.
One call or several?
Both forms give the same result. These two chains are equivalent:
one_call = df.assign(
revenue=lambda d: d["price"] * d["quantity"],
share=lambda d: d["revenue"] / d["revenue"].sum(),
)
two_calls = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.assign(share=lambda d: d["revenue"] / d["revenue"].sum())
)Some guidance for choosing:
| Situation | Better choice |
|---|---|
| Columns form one logical unit (revenue, tax, total) | One call |
| A filter or other method must run between the columns | Separate calls |
| A later column depends on the result of `query` or `sort_values` | Separate calls |
| Each lambda is long and hard to scan | Separate calls, so each step stands out |
| Many unrelated columns | One call per theme, or a `pipe` function |
The separate-call form is required when something must happen between the two columns. For example, a cumulative_share column that depends on sorted order needs the sort first:
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.sort_values("revenue", ascending=False)
.assign(cumulative=lambda d: d["revenue"].cumsum())
)If you put cumulative in the first assign, it would be computed before the sort and in the wrong order.
Common mistakes
- Wrong order. A keyword refers to a column that a later keyword creates. This produces a
KeyError. Reorder the keywords. - Plain values instead of lambdas. A Series built from
dfcannot see columns from the same call and ignores earlier chain steps. Use lambdas. - Unintended overwrite. A name you meant to be new matches an existing column, and
assignsilently replaces it. Checkdf.columnswhen a result looks wrong. - Loop lambdas. Use a default argument to capture the loop variable.
- Hidden dependencies on the whole frame.
d["revenue"].sum()is computed over every row at that moment. If rows are filtered later, the share no longer adds up to 1. Compute shares after the final filter.
Exercises
Exercise
This call raises a KeyError. Explain why, and fix it with the smallest change. df.assign( share=lambda d: d["revenue"] / d["revenue"].sum(), revenue=lambda d: d["price"] * d["quantity"], )
Show answer
assign evaluates keywords in the order written. The share lambda runs first, on a copy that does not yet have a revenue column, so d["revenue"] raises KeyError. Swap the two keywords so revenue comes first. The share lambda then sees the revenue column that the first lambda added to the copy.
Exercise
Write one assign call that, on the order data, creates revenue (price times quantity), then islarge (True when revenue is greater than the mean revenue of the rows in the DataFrame at that point). Then explain what islarge would be if you wrote revenue=df["price"] * df["quantity"] as a plain Series and is_large as a lambda.
Show answer
df.assign(revenue=lambda d: d["price"] * d["quantity"], islarge=lambda d: d["revenue"] > d["revenue"].mean()). With a plain Series for revenue, the column is still created, because the plain Series only uses columns from the original df, and the lambda for islarge then sees it. The result is the same for this standalone call. The plain form breaks in a longer chain: if an earlier step such as query had filtered the rows, df["price"] would still refer to the unfiltered original frame and would not match the filtered rows, so the lambda form is the safe habit.