Each keyword argument to assign() becomes a new column name, and its value, either a fixed value/Series or a function taking the DataFrame and returning a Series, becomes that column's data — passing a function specifically lets you reference other columns being computed in the same assign() call, evaluated in the order the keyword arguments are given. Unlike directly assigning to a new column on df, assign() always returns a brand-new DataFrame and never modifies the original in place, which makes it a natural fit for chaining a sequence of transformations together in one fluent expression.
1Understanding df.assign()
Each keyword argument to assign() becomes a new column name, and its value, either a fixed value/Series or a function taking the DataFrame and returning a Series, becomes that column's data — passing a function specifically lets you reference other columns being computed in the same assign() call, evaluated in the order the keyword arguments are given. Unlike directly assigning to a new column on df, assign() always returns a brand-new DataFrame and never modifies the original in place, which makes it a natural fit for chaining a sequence of transformations together in one fluent expression.
Use a lambda inside assign() that receives the intermediate DataFrame as its parameter, instead of referencing the original df directly, when you need the new column to depend on another column also being created earlier in the same assign() call.
import pandas as pd
df = pd.DataFrame({"price": [10, 20], "quantity": [3, 2]})
new_df = df.assign(total=df["price"] * df["quantity"])
print(new_df)2Practical Example
Here is a real-world application of df.assign() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"price": [10, 20], "quantity": [3, 2]})
result = df.assign(total=lambda d: d["price"] * d["quantity"], tax=lambda d: d["total"] * 0.08)
print(result)3Best Practices
Follow these guidelines when working with df.assign():
1. Use assign() when you want to add a computed column without mutating the original DataFrame, especially in the middle of a chained sequence of operations
2. Use a lambda referencing the DataFrame parameter, rather than the outer df variable, inside assign() when a new column depends on another one being created in the same call
3. Prefer plain direct column assignment for simple, one-off cases where the fluent, chainable style of assign() isn't actually needed
Tip: Use a lambda inside assign() that receives the intermediate DataFrame as its parameter, instead of referencing the original df directly, when you need the new column to depend on another column also being created earlier in the same assign() call.
import pandas as pd
df = pd.DataFrame({"price": [10, 20], "quantity": [3, 2]})
new_df = df.assign(total=df["price"] * df["quantity"])
print(new_df)