Sub topic 2
Adding Columns with `assign`
Assume you know basic Python functions and lambdas, can create and filter pandas DataFrames, and understand basic groupby aggregation.
Adding columns with `assign`
assign returns a new DataFrame with the requested columns. It does not change the original DataFrame in place. This makes it useful in method chains.
import pandas as pd
df = pd.DataFrame({
"price": [10.0, 20.0, 15.0],
"quantity": [2, 1, 3],
})
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.query("revenue > 20")
)
print(result)The revenue column is calculated first. The following query call receives the new DataFrame.
Why `assign` takes lambdas
A callable, such as a lambda, receives the current DataFrame. This matters when the expression refers to a column created earlier in the chain.
Without a lambda, Python evaluates the expression before assign receives the DataFrame. The lambda delays evaluation until pandas has the correct intermediate object.
result = (
df
.assign(
revenue=lambda d: d["price"] * d["quantity"],
margin=lambda d: d["revenue"] * 0.2,
)
)Here, margin can use revenue because keyword arguments to assign are evaluated in order.
Several dependent columns in one `assign`
You can create multiple columns in one call. Each callable sees the DataFrame as it exists at that point, including columns created earlier in the same call.
result = (
df
.assign(
revenue=lambda d: d["price"] * d["quantity"],
share=lambda d: d["revenue"] / d["revenue"].sum(),
)
)An existing column is replaced when you use its name again:
result = df.assign(price=lambda d: d["price"] * 1.1)Column names with spaces or reserved characters
Keyword arguments must be valid Python identifiers. For a column name such as unit price, unpack a dictionary with **.
result = (
df
.assign(**{
"unit price": lambda d: d["revenue"] / d["quantity"]
})
)Use bracket notation to select that column: result["unit price"].
Exercise
Why does margin=lambda d: d["revenue"] * 0.2 work after creating revenue in the same assign call?
Show answer
assign evaluates its keyword arguments in order, and each callable receives the current DataFrame.