The transform() function helps you change data within groups while keeping the original data shape. It lets you add new info or adjust values based on group details.
transform() for group-level operations in Data Analysis Python
DataFrame.groupby('column')['target_column'].transform(function)
The transform() applies a function to each group and returns a result with the same size as the original data.
This means you can add or replace columns without changing the number of rows.
df.groupby('Team')['Score'].transform('mean')
df.groupby('Category')['Value'].transform(lambda x: x - x.min())
df.groupby('Group')['Sales'].transform('max')
This code creates a table of players with their scores and teams. It then adds the average score for each team to every player in that team. Finally, it shows how much each player's score differs from their team's average.
import pandas as pd data = {'Team': ['A', 'A', 'B', 'B', 'B'], 'Player': ['John', 'Mike', 'Anna', 'Tom', 'Sara'], 'Score': [10, 15, 10, 20, 30]} df = pd.DataFrame(data) # Calculate average score per team and add as new column df['Team_Avg'] = df.groupby('Team')['Score'].transform('mean') # Calculate score difference from team average df['Diff_from_Avg'] = df['Score'] - df['Team_Avg'] print(df)
transform() keeps the original number of rows, unlike agg() which reduces rows.
You can use built-in functions like 'mean', 'max', or your own custom functions with lambda.
It is useful when you want to add group-level info back to the original data.
transform() applies a function to groups and returns a result matching the original data size.
It helps add or adjust columns based on group calculations without changing row count.
Use it to compare individual values to group stats or fill missing data within groups.
Practice
transform() function do when used on a grouped DataFrame in pandas?Solution
Step 1: Understand the purpose of
Thetransform()transform()function applies a function to each group but keeps the original DataFrame size by returning a transformed value for each row.Step 2: Compare with other group operations
Unlike aggregation which reduces group size,transform()returns a result aligned with the original data rows.Final Answer:
Applies a function to each group and returns a result with the same size as the original DataFrame -> Option AQuick Check:
transform()keeps original size [OK]
- Confusing transform with aggregate which reduces size
- Thinking transform filters groups
- Assuming transform sorts data
transform() on a grouped DataFrame df grouped by column 'A' to calculate the mean of column 'B' for each group?Solution
Step 1: Identify grouping and column selection
We groupdfby column'A'and want to transform column'B'by calculating its mean per group.Step 2: Check syntax correctness
The correct syntax isdf.groupby('A')['B'].transform('mean')which applies mean to each group of 'B' and returns a Series aligned with original rows.Final Answer:
df.groupby('A')['B'].transform('mean') -> Option BQuick Check:
Group by 'A', transform 'B' with mean [OK]
- Applying transform before groupby
- Grouping by wrong column
- Selecting wrong column for transform
df below:Team Score 0 A 10 1 A 20 2 B 30 3 B 40 4 B 50
What is the output of
df.groupby('Team')['Score'].transform(lambda x: x - x.mean())?Solution
Step 1: Calculate group means
Group A scores: 10, 20 -> mean = 15
Group B scores: 30, 40, 50 -> mean = 40Step 2: Subtract group mean from each score
For group A: 10-15 = -5, 20-15 = 5
For group B: 30-40 = -10, 40-40 = 0, 50-40 = 10Final Answer:
[-5.0, 5.0, -10.0, 0.0, 10.0] -> Option AQuick Check:
Subtract mean per group [OK]
- Calculating overall mean instead of group mean
- Using aggregate instead of transform
- Misaligning output length
df.groupby('Category')['Value'].transform(np.sum)It raises an error:
NameError: name 'np' is not defined. How can you fix it?Solution
Step 1: Identify cause of error
The errorNameError: name 'np' is not definedmeans numpy was not imported but used asnp.Step 2: Fix by importing numpy
Addimport numpy as npat the start of the script to definenp.Final Answer:
Addimport numpy as npbefore the code -> Option CQuick Check:
Import libraries before use [OK]
- Trying to use transform before groupby
- Misplacing groupby and transform order
- Replacing transform with aggregate without reason
df with columns 'Store', 'Sales', and some missing 'Sales' values. You want to fill missing 'Sales' with the average sales of the respective 'Store'. Which code correctly uses transform() to do this?Solution
Step 1: Understand the goal
We want to fill missing'Sales'values with the average sales per'Store'. The average per store must align with each row.Step 2: Use transform to get group means aligned to rows
df.groupby('Store')['Sales'].transform('mean')returns a Series with the mean sales per store repeated for each row.Step 3: Fill missing values with these means
Usefillna()on'Sales'column with the transformed means to fill missing values correctly.Final Answer:
df['Sales'] = df['Sales'].fillna(df.groupby('Store')['Sales'].transform('mean')) -> Option DQuick Check:
Fill missing with group mean using transform [OK]
- Using aggregate mean which returns smaller Series
- Filling missing before grouping
- Misusing fillna with wrong data shape
Ready to prove it?
Pass the test and this pattern moves unknown
