Bird
Raised Fist0
Pandasdata~20 mins

transform() for group-level operations in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Transform Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of group transform with mean subtraction
What is the output of the following code snippet?
Pandas
import pandas as pd

df = pd.DataFrame({'Team': ['A', 'A', 'B', 'B'], 'Points': [10, 20, 30, 40]})
df['AdjPoints'] = df.groupby('Team')['Points'].transform(lambda x: x - x.mean())
print(df)
A
  Team  Points  AdjPoints
0    A      10       -5.0
1    A      20        5.0
2    B      30       -5.0
3    B      40        5.0
B
  Team  Points  AdjPoints
0    A      10       10.0
1    A      20       20.0
2    B      30       30.0
3    B      40       40.0
C
  Team  Points  AdjPoints
0    A      10       15.0
1    A      20       15.0
2    B      30       35.0
3    B      40       35.0
D
  Team  Points  AdjPoints
0    A      10       -10.0
1    A      20       10.0
2    B      30       -30.0
3    B      40       30.0
Attempts:
2 left
💡 Hint
Think about what subtracting the group mean from each value does.
❓ data_output
intermediate
1:30remaining
Number of items after transform with duplicated values
Given the code below, how many rows does the resulting DataFrame have?
Pandas
import pandas as pd

df = pd.DataFrame({'Category': ['X', 'X', 'Y', 'Y', 'Y'], 'Value': [1, 2, 3, 4, 5]})
df['Rank'] = df.groupby('Category')['Value'].transform('rank')
print(len(df))
A5
B3
C2
D1
Attempts:
2 left
💡 Hint
transform keeps the original DataFrame shape.
🔧 Debug
advanced
2:00remaining
Identify the error in transform usage
What error does the following code raise?
Pandas
import pandas as pd

df = pd.DataFrame({'Group': ['G1', 'G1', 'G2'], 'Score': [10, 20, 30]})
df['Scaled'] = df.groupby('Group')['Score'].transform(lambda x: x / x.sum())
print(df)
ATypeError: unsupported operand type(s) for /: 'int' and 'method'
BNo error, outputs scaled scores per group
CAttributeError: 'SeriesGroupBy' object has no attribute 'sum'
DValueError: Length of values does not match length of index
Attempts:
2 left
💡 Hint
Check if the lambda function uses correct pandas methods.
🚀 Application
advanced
2:30remaining
Using transform to fill missing values with group mean
You have a DataFrame with missing values in the 'Sales' column. Which code snippet correctly fills missing 'Sales' values with the mean sales of their group in 'Region'?
Pandas
import pandas as pd
import numpy as np

df = pd.DataFrame({'Region': ['East', 'East', 'West', 'West'], 'Sales': [100, np.nan, 200, np.nan]})
Adf['Sales'] = df['Sales'].fillna(df.groupby('Region')['Sales'].mean())
Bdf['Sales'] = df.groupby('Region')['Sales'].transform('mean')
Cdf['Sales'] = df.groupby('Region')['Sales'].apply(lambda x: x.fillna(x.mean()))
Ddf['Sales'] = df.groupby('Region')['Sales'].transform(lambda x: x.fillna(x.mean()))
Attempts:
2 left
💡 Hint
transform keeps the original index and shape, apply may change it.
🧠 Conceptual
expert
2:00remaining
Why use transform instead of apply for group-level operations?
Which statement best explains why transform is preferred over apply for group-level operations that return a Series with the same shape as the original DataFrame?
Aapply always returns a DataFrame, transform always returns a scalar.
Bapply is faster than transform but cannot handle group operations.
Ctransform returns a Series aligned with the original DataFrame, preserving index and shape, while apply may return aggregated or differently shaped results.
Dtransform can only be used with numeric data, apply works with all data types.
Attempts:
2 left
💡 Hint
Think about the shape and alignment of the output.

Practice

(1/5)
1. What does the transform() function do when used on a grouped pandas DataFrame?
easy
A. Applies a function to each group and returns a result with the same size as the original data
B. Aggregates each group into a single summary value
C. Filters out groups based on a condition
D. Sorts the groups in ascending order

Solution

  1. Step 1: Understand the purpose of transform()

    transform() applies a function to each group but returns a result with the same number of rows as the original DataFrame.
  2. Step 2: Compare with other group operations

    Unlike aggregation which reduces groups to single values, transform() keeps the original data size, allowing new columns with group-level info.
  3. Final Answer:

    Applies a function to each group and returns a result with the same size as the original data -> Option A
  4. Quick Check:

    transform() = same size output [OK]
Hint: Remember: transform keeps original rows, aggregation reduces them [OK]
Common Mistakes:
  • Confusing transform with aggregation
  • Thinking transform filters groups
  • Assuming transform changes group order
2. Which of the following is the correct syntax to use transform() to calculate the mean of each group in a DataFrame df grouped by column 'Category'?
easy
A. df.groupby('Category').mean().transform()
B. df.groupby('Category').transform('mean')
C. df.transform('mean').groupby('Category')
D. df.groupby('Category').apply(transform('mean'))

Solution

  1. Step 1: Identify correct method chaining

    First group by 'Category' then call transform('mean') to apply mean to each group and keep original size.
  2. Step 2: Check other options for syntax errors

    df.transform('mean').groupby('Category') calls transform before grouping, which is invalid. df.groupby('Category').mean().transform() calls mean before transform, which is wrong order. df.groupby('Category').apply(transform('mean')) misuses apply with transform.
  3. Final Answer:

    df.groupby('Category').transform('mean') -> Option B
  4. Quick Check:

    Group first, then transform [OK]
Hint: Group first, then call transform with function name [OK]
Common Mistakes:
  • Calling transform before groupby
  • Using apply incorrectly with transform
  • Calling aggregation before transform
3. Given the DataFrame df below:
  Category  Value
0        A      5
1        A      7
2        B      3
3        B      9
4        B      6

What is the output of df.groupby('Category')['Value'].transform('max')?
medium
A. [6, 6, 9, 9, 9]
B. [5, 7, 3, 6, 9]
C. [7, 5, 9, 3, 6]
D. [7, 7, 9, 9, 9]

Solution

  1. Step 1: Group by 'Category' and find max per group

    Group A has values [5,7], max is 7; Group B has [3,9,6], max is 9.
  2. Step 2: Apply transform to assign max to each row in group

    Rows in group A get 7, rows in group B get 9, preserving original row order.
  3. Final Answer:

    [7, 7, 9, 9, 9] -> Option D
  4. Quick Check:

    Max per group repeated for each row [OK]
Hint: transform repeats group result for each row [OK]
Common Mistakes:
  • Confusing transform output with aggregation output
  • Mixing up max values per group
  • Not preserving original row order
4. Consider this code snippet:
df = pd.DataFrame({'Group': ['X', 'X', 'Y'], 'Score': [10, 20, 30]})
df['MeanScore'] = df.groupby('Group')['Score'].transform(mean)

What is the error in this code?
medium
A. The function name 'mean' should be a string: 'mean'
B. Group column name is incorrect
C. transform() cannot be used with mean function
D. DataFrame creation syntax is wrong

Solution

  1. Step 1: Check function argument in transform

    The function mean is passed without quotes, but transform expects a string or a callable.
  2. Step 2: Correct usage

    Passing 'mean' as a string fixes the error: transform('mean').
  3. Final Answer:

    The function name 'mean' should be a string: 'mean' -> Option A
  4. Quick Check:

    Function names in transform must be strings or callables [OK]
Hint: Use quotes around function names in transform [OK]
Common Mistakes:
  • Passing function name without quotes
  • Assuming transform can't use built-in functions
  • Misnaming DataFrame columns
5. You have a DataFrame df with columns 'Team' and 'Points'. You want to add a new column 'PointsDiff' that shows the difference between each player's points and the average points of their team. Which code correctly uses transform() to achieve this?
hard
A. df['PointsDiff'] = df.groupby('Team')['Points'].mean() - df['Points']
B. df['PointsDiff'] = df.groupby('Team')['Points'].transform(lambda x: x.mean())
C. df['PointsDiff'] = df['Points'] - df.groupby('Team')['Points'].transform('mean')
D. df['PointsDiff'] = df.groupby('Team')['Points'].apply(lambda x: x.mean())

Solution

  1. Step 1: Calculate team average points with transform

    Use transform('mean') to get average points per team for each row, preserving size.
  2. Step 2: Subtract team average from each player's points

    Subtract the transformed mean from the original 'Points' column to get difference per player.
  3. Step 3: Check other options

    df['PointsDiff'] = df.groupby('Team')['Points'].mean() - df['Points']: df.groupby('Team')['Points'].mean() returns smaller Series, size mismatch. df['PointsDiff'] = df.groupby('Team')['Points'].transform(lambda x: x.mean()): transform(lambda x: x.mean()) sets PointsDiff to repeated group means, not differences. df['PointsDiff'] = df.groupby('Team')['Points'].apply(lambda x: x.mean()): apply(lambda x: x.mean()) returns smaller Series of means, misalignment.
  4. Final Answer:

    df['PointsDiff'] = df['Points'] - df.groupby('Team')['Points'].transform('mean') -> Option C
  5. Quick Check:

    Subtract group mean using transform for aligned output [OK]
Hint: Subtract transform('mean') result from original column [OK]
Common Mistakes:
  • Using apply instead of transform causing misalignment
  • Not subtracting in correct order
  • Confusing transform with aggregation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard