transform: Same Shape Back
transform gives back a result the same shape as the frame. Each row keeps its place and gains its group value.
Group mean on every row
transform sends the group mean back to each row. Both Drink rows gain the same mean.
import pandas as pd
df = pd.DataFrame({
"product": ["Tea", "Coffee", "Mug"],
"category": ["Drink", "Drink", "Home"],
"units": [2, 1, 3],
})
df["avg_units"] = df.groupby("category")["units"].transform("mean")
print(df)Share of the group total
Each row divides its units by its group total. Tea holds two thirds of the Drink total.
import pandas as pd
df = pd.DataFrame({
"product": ["Tea", "Coffee", "Mug"],
"category": ["Drink", "Drink", "Home"],
"units": [2, 1, 3],
})
df["share"] = df["units"] / df.groupby("category")["units"].transform("sum")
print(df)Example
import io
import pandas as pd
SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""
sales = pd.read_csv(io.StringIO(SALES_CSV))
sales["avg_price"] = sales.groupby("category")["price"].transform("mean")
sales["price_gap"] = sales["price"] - sales["avg_price"]
print(sales[["product", "category", "price", "avg_price", "price_gap"]])Key points
- Use transform to send a group summary back to every row.
- The result has one value per row, in the same order as the frame.
- Subtract the group mean to centre each row on its group.
- Divide by the group total to find each row share of its group.
In this example, the sales table loads from the CSV text. transform sends the average price of each category back to every row. price_gap subtracts that average from each price. A Mug at 12.0 sits 6.0 below the Home average of 18.0.
Note
agg shrinks each group to one row. transform keeps every row.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
transform returns a result with what shape?