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. It also assumes you know that df["new"] = ... adds a column by assignment.
Why assign() exists
Direct assignment changes the DataFrame in place. That is fine in a script, but it breaks a method chain, because the assignment statement returns nothing. DataFrame.assign() does the same job and returns a new DataFrame. You can then call another method on the result.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
df2 = df.assign(total=df["price"] * df["qty"])
print(df.columns.tolist())
print(df2.columns.tolist())The first print shows ['item', 'price', 'qty']. The second shows ['item', 'price', 'qty', 'total']. The original df is unchanged.
Using lambdas to refer to the current frame
In the example above, df["price"] refers to the original df. In a long chain, that variable may no longer match the data at that step. To avoid this, pass a function. assign() calls it with the DataFrame as built so far.
df = df.assign(
total=lambda d: d["price"] * d["qty"],
total_with_tax=lambda d: d["total"] * 1.2,
)
print(df)Keyword arguments are evaluated in order. total_with_tax can use total because total was created first. This only works when you use a lambda. If you wrote df["total"] * 1.2 directly, Python would look for total before assign() ran, and you would get a KeyError.
Using assign() in a chain
Each step passes its result to the next, so you can read the pipeline from top to bottom.
result = (
pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
.assign(total=lambda d: d["price"] * d["qty"])
.query("total > 15")
.assign(share=lambda d: d["total"] / d["total"].sum())
.sort_values("share", ascending=False)
)
print(result)The query() step drops the pen row, which has a total of 15.0. The second assign() then computes shares only over the remaining rows. A lambda matters here, because the filtered frame has no variable name you could refer to.
Common errors
- Column names that are not valid keywords. Keyword arguments must be valid Python identifiers. For a name like
"unit price", unpack a dictionary:df.assign(**{"unit price": df["price"]}). - Forgetting to keep the result.
df.assign(x=1)on its own line does nothing lasting. Assign it back withdf = df.assign(x=1), or store it in a new name. - Reusing a column in the same call without a lambda. Only callables see columns created earlier in the same call.
- Overwriting by accident. If the name already exists,
assign()replaces that column in the returned frame.
Exercise
Given a DataFrame df with a price column, write one assign() call that adds discounted (price times 0.9) and then rounded (discounted rounded to one decimal place). Why must rounded use a lambda?
Show answer
df.assign(discounted=lambda d: d["price"] * 0.9, rounded=lambda d: d["discounted"].round(1)). The discounted column does not exist in df yet when Python evaluates the arguments. The lambda is called later, with the frame that already includes discounted.