Assign new columns to a DataFrame using the Pandas assign() method. Create derived calculations, enable method chaining, use lambda expressions for sequential updates, and return new objects without mutating the original DataFrame.
assign() method creates and adds new columns to a DataFrame or overwrites existing ones. Unlike standard column assignment (e.g., df["new"] = ...), assign() returns a fresh DataFrame copy, making it indispensable for functional programming and method chaining pipelines.import pandas as pd
df = pd.DataFrame({
"PRODUCT": ["Pen", "Pencil", "Notebook", "Eraser"],
"QTY": [10, 25, 5, 40],
"PRICE": [15.0, 5.0, 80.0, 3.0]
})
print(df)
assert df.shape == (4, 3)
Expected output
PRODUCT QTY PRICE
0 Pen 10 15.0
1 Pencil 25 5.0
2 Notebook 5 80.0
3 Eraser 40 3.0
assign() where the keyword name specifies the new column name and the value supplies the calculated Series.df_total = df.assign(TOTAL_VALUE=df["QTY"] * df["PRICE"])
print(df_total)
assert df_total.loc[0, "TOTAL_VALUE"] == 150.0 and "TOTAL_VALUE" not in df.columns
Expected output
PRODUCT QTY PRICE TOTAL_VALUE
0 Pen 10 15.0 150.0
1 Pencil 25 5.0 125.0
2 Notebook 5 80.0 400.0
3 Eraser 40 3.0 120.0
assign() lets you reference the dynamically updated DataFrame within a method chain.df_chained = (
df.query("QTY > 8")
.assign(TOTAL=lambda x: x["QTY"] * x["PRICE"])
.assign(TAX=lambda x: x["TOTAL"] * 0.1)
)
print(df_chained)
assert df_chained.loc[0, "TAX"] == 15.0
Expected output
PRODUCT QTY PRICE TOTAL TAX
0 Pen 10 15.0 150.0 15.0
1 Pencil 25 5.0 125.0 12.5
3 Eraser 40 3.0 120.0 12.0
assign() call. In Python 3.6+, keyword arguments are evaluated in order, allowing subsequent lambdas to access newly created columns.df_multi = df.assign(
DISCOUNT_PRICE=lambda x: x["PRICE"] * 0.9,
FINAL_TOTAL=lambda x: x["QTY"] * x["DISCOUNT_PRICE"]
)
print(df_multi)
assert df_multi.loc[0, "FINAL_TOTAL"] == 135.0
Expected output
PRODUCT QTY PRICE DISCOUNT_PRICE FINAL_TOTAL
0 Pen 10 15.0 13.5 135.0
1 Pencil 25 5.0 4.5 112.5
2 Notebook 5 80.0 72.0 360.0
3 Eraser 40 3.0 2.7 108.0
MARKS = [80, 90, 70]. Use assign() with a lambda expression to create a column PERCENTAGE dividing MARKS by 100.0 and scaling to 100. Verify that the max percentage equals 90.0.assign().ex_df = pd.DataFrame({"MARKS": [80, 90, 70]})
answer = ex_df.assign(PERCENTAGE=lambda x: (x["MARKS"] / 100.0) * 100)
print(answer)
assert answer["PERCENTAGE"].max() == 90.0
Expected output
MARKS PERCENTAGE
0 80 80.0
1 90 90.0
2 70 70.0
Practice assign() examples interactively directly in your browser:
Reference: Pandas assign() documentation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.