Sub topic 7
Several dependent columns in one assign
This chapter assumes you know basic Python, can build and inspect a DataFrame, and have used assign with a lambda to add one column. Here you will create several columns in a single assign call, where later columns use earlier ones.
One call, several columns
assign accepts any number of keyword arguments. Each keyword becomes a column name, and each value can be a lambda that receives the DataFrame. You could write one assign per column and chain them. You can also put all the columns in one call when they belong together.
The rule that makes this work is that the keyword arguments are evaluated in the order you write them. A lambda later in the list sees a DataFrame that already contains the columns defined before it.
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],
})
result = (
df
.assign(
revenue=lambda d: d["price"] * d["quantity"],
share=lambda d: d["revenue"] / d["revenue"].sum(),
)
)
print(result)The share lambda reads d["revenue"]. That column does not exist in df. It exists because assign added revenue first, then called the second lambda with the updated frame.
The output looks like this:
order_id region price quantity revenue share
0 1 east 10.0 2 20.0 0.173913
1 2 west 20.0 1 20.0 0.173913
2 3 east 15.0 3 45.0 0.391304
3 4 west 5.0 10 30.0 0.260870How the order is processed
The call is equivalent to a sequence of single-column steps. The diagram shows the data flow.
This ordering relies on keyword arguments keeping the order in which you wrote them. Python guarantees this for keyword arguments (since version 3.6, and officially since 3.7), and pandas 0.23 and later depends on it. If you work with a very old setup, split the columns into separate assign calls.
Dependent columns versus a single expression
Compare two ways of writing the same result. The first computes revenue twice.
result = df.assign(
revenue=lambda d: d["price"] * d["quantity"],
share=lambda d: (d["price"] * d["quantity"]) / (d["price"] * d["quantity"]).sum(),
)The second reuses revenue as shown earlier. It is shorter, avoids repeated logic, and gives each step a name. If you change the revenue formula, you edit one line.
Mixing in a column that is not a lambda
A value does not have to be a lambda. It can be a constant or a Series. A constant is broadcast to every row, which is useful for labels.
result = df.assign(
source="web",
revenue=lambda d: d["price"] * d["quantity"],
big_order=lambda d: d["revenue"] > 20,
)
print(result[["order_id", "source", "revenue", "big_order"]])Note that big_order still needs a lambda. A plain expression such as df["revenue"] > 20 would be evaluated before assign runs, and df has no revenue column yet. This raises a KeyError.
Common errors
- Referencing
dfinstead of the lambda argument. Inside a chain,dfis the original frame, not the intermediate one. Uselambda d: d[...]. - Using a column before it is defined. If
shareis listed beforerevenue, thesharelambda fails with aKeyError. Reorder the keywords. - Replacing a column you still need. If you write
price=lambda d: d["price"] * 2and thenrevenue=lambda d: d["price"] * d["quantity"], the revenue uses the doubled price. This is correct behavior, but it surprises people. Order your keywords on purpose.
Exercise
Given the DataFrame df above, write an assign call that creates three columns in one call: revenue (price times quantity), tax (20 percent of revenue), and total (revenue plus tax). Why does the order of the keyword arguments matter?
Show answer
df.assign(revenue=lambda d: d["price"] d["quantity"], tax=lambda d: d["revenue"] 0.2, total=lambda d: d["revenue"] + d["tax"]). The keyword arguments are evaluated in the order written, so tax can use revenue and total can use both revenue and tax. If total came first, d["tax"] would not exist yet and pandas would raise a KeyError.