Bird
Raised Fist0
Pandasdata~20 mins

Named aggregation in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Named Aggregation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of named aggregation with multiple functions
What is the output DataFrame after running this code with named aggregation?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Team': ['A', 'A', 'B', 'B', 'C'],
    'Points': [10, 15, 10, 20, 30],
    'Assists': [5, 7, 8, 6, 10]
})

result = df.groupby('Team').agg(
    total_points=pd.NamedAgg(column='Points', aggfunc='sum'),
    max_assists=pd.NamedAgg(column='Assists', aggfunc='max')
)
print(result)
A{'Team': ['A', 'B', 'C'], 'total_points': [25, 30, 30], 'max_assists': [7, 8, 10]}
B
       total_points  max_assists
Team                            
A                25            7
B                30            8
C                30           10
C
Team
A    total_points    25
     max_assists      7
B    total_points    30
     max_assists      8
C    total_points    30
     max_assists     10
dtype: int64
D
       Points  Assists
Team                  
A          25       12
B          30       14
C          30       10
Attempts:
2 left
💡 Hint
Look at how named aggregation creates new columns with the given names.
❓ data_output
intermediate
1:30remaining
Number of rows in named aggregation result
Given this DataFrame and named aggregation, how many rows does the result have?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Category': ['X', 'X', 'Y', 'Z', 'Z', 'Z'],
    'Value': [1, 2, 3, 4, 5, 6]
})

result = df.groupby('Category').agg(
    sum_value=pd.NamedAgg(column='Value', aggfunc='sum'),
    count_value=pd.NamedAgg(column='Value', aggfunc='count')
)
print(len(result))
A3
B6
C2
D1
Attempts:
2 left
💡 Hint
Count unique groups in the 'Category' column.
🔧 Debug
advanced
2:00remaining
Identify the error in named aggregation syntax
What error does this code raise?
Pandas
import pandas as pd

df = pd.DataFrame({'A': [1,2,3], 'B': [4,5,6]})

result = df.groupby('A').agg(
    total_B=('B', 'sum'),
    mean_B='mean'
)
print(result)
ATypeError: named aggregation expects keyword arguments
BSyntaxError: invalid syntax
CKeyError: 'mean_B'
DNo error, prints grouped DataFrame
Attempts:
2 left
💡 Hint
Check how named aggregation arguments are passed.
🚀 Application
advanced
2:30remaining
Create a named aggregation to find min and max
Which option correctly uses named aggregation to find min and max of 'Score' grouped by 'Group'?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Group': ['G1', 'G1', 'G2', 'G2'],
    'Score': [88, 92, 85, 90]
})

result = df.groupby('Group').agg(
    min_score=...,  # fill here
    max_score=...   # fill here
)
print(result)
A{'min_score': ('Score', 'min'), 'max_score': ('Score', 'max')}
Bmin_score=('Score', 'min'), max_score=('Score', 'max')
Cmin_score='min', max_score='max'
Dmin_score=pd.NamedAgg(column='Score', aggfunc='min'), max_score=pd.NamedAgg(column='Score', aggfunc='max')
Attempts:
2 left
💡 Hint
Named aggregation uses pd.NamedAgg or keyword tuples.
🧠 Conceptual
expert
3:00remaining
Understanding output structure of named aggregation
After applying named aggregation with multiple functions on different columns, what is the structure of the resulting DataFrame?
AA MultiIndex DataFrame with original column names as first level and aggregation functions as second level.
BA Series with group keys as index and tuples of aggregated values as elements.
CA DataFrame indexed by group keys with columns named as specified in named aggregation, each column holding aggregated values.
DA DataFrame with original columns replaced by aggregated columns without group keys as index.
Attempts:
2 left
💡 Hint
Named aggregation creates new columns with given names and keeps group keys as index.

Practice

(1/5)
1. What is the main purpose of named aggregation in pandas?
easy
A. To assign custom names to aggregated summary columns
B. To rename columns before aggregation
C. To filter rows before grouping
D. To sort data after aggregation

Solution

  1. Step 1: Understand aggregation in pandas

    Aggregation combines data by groups to produce summary statistics.
  2. Step 2: Role of named aggregation

    Named aggregation lets you specify clear names for these summary columns, making results easier to read.
  3. Final Answer:

    To assign custom names to aggregated summary columns -> Option A
  4. Quick Check:

    Named aggregation = custom summary names [OK]
Hint: Named aggregation means naming summary columns clearly [OK]
Common Mistakes:
  • Confusing named aggregation with renaming columns before aggregation
  • Thinking it filters or sorts data
  • Assuming it changes the grouping keys
2. Which of the following is the correct syntax for using named aggregation in groupby.agg()?
easy
A. df.groupby('A').agg({'new_col': 'B', 'sum'})
B. df.groupby('A').agg('new_col' = ('B', 'sum'))
C. df.groupby('A').agg(new_col=('B', 'sum'))
D. df.groupby('A').agg(('B', 'sum') = 'new_col')

Solution

  1. Step 1: Recall named aggregation syntax

    Named aggregation uses keyword arguments with the format new_name=(column, function).
  2. Step 2: Check each option

    df.groupby('A').agg(new_col=('B', 'sum')) matches this syntax exactly: new_col=('B', 'sum'). Others have invalid syntax or misplaced equals signs.
  3. Final Answer:

    df.groupby('A').agg(new_col=('B', 'sum')) -> Option C
  4. Quick Check:

    Named aggregation syntax = new_name=(col, func) [OK]
Hint: Use new_name=(column, function) inside agg() [OK]
Common Mistakes:
  • Using equals sign inside dictionary instead of keyword argument
  • Misplacing parentheses or quotes
  • Trying to assign new_col outside agg()
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({'Team': ['A', 'A', 'B', 'B'], 'Points': [10, 15, 10, 20], 'Assists': [5, 7, 8, 6]})
result = df.groupby('Team').agg(total_points=('Points', 'sum'), max_assists=('Assists', 'max'))
print(result)

What is the output?
medium
A. Team index with total_points as sum of Points and max_assists as max of Assists
B. DataFrame with columns Points and Assists unchanged
C. Error because named aggregation syntax is wrong
D. Empty DataFrame because groupby is missing

Solution

  1. Step 1: Understand the groupby and aggregation

    Grouping by 'Team' groups rows by 'A' and 'B'. Then sum Points and max Assists per group.
  2. Step 2: Check named aggregation results

    total_points sums Points per team: A=10+15=25, B=10+20=30; max_assists picks max Assists per team: A=max(5,7)=7, B=max(8,6)=8.
  3. Final Answer:

    Team index with total_points as sum of Points and max_assists as max of Assists -> Option A
  4. Quick Check:

    Named aggregation sums and maxes grouped data [OK]
Hint: Sum and max per group with named aggregation [OK]
Common Mistakes:
  • Expecting original columns unchanged
  • Confusing max with sum
  • Thinking groupby needs reset_index() to work
4. What is wrong with this code snippet?
df.groupby('Category').agg(total=('Value', 'sum'), mean='Value')
medium
A. The sum function cannot be used with named aggregation
B. The groupby column 'Category' does not exist
C. The agg method requires a list, not keyword arguments
D. The mean aggregation is missing the function tuple syntax

Solution

  1. Step 1: Review named aggregation syntax

    Each named aggregation must be a keyword argument with a tuple: new_name=(column, function).
  2. Step 2: Identify the error

    The 'mean' aggregation is given as mean='Value' without specifying the aggregation function, which is incorrect.
  3. Final Answer:

    The mean aggregation is missing the function tuple syntax -> Option D
  4. Quick Check:

    Named aggregation needs (column, function) tuples [OK]
Hint: Each agg must be new_name=(col, func) [OK]
Common Mistakes:
  • Passing column name as string without function
  • Assuming agg accepts mixed syntax
  • Using list instead of keyword arguments
5. You have a DataFrame with sales data:
import pandas as pd
df = pd.DataFrame({'Store': ['X', 'X', 'Y', 'Y', 'Z'], 'Sales': [100, 150, 200, 250, 300], 'Returns': [5, 3, 2, 4, 1]})

You want to create a summary DataFrame grouped by 'Store' with:
  • Total sales named 'total_sales'
  • Average returns named 'avg_returns'
  • Count of sales entries named 'sales_count'

Which code correctly uses named aggregation to achieve this?
hard
A. df.groupby('Store').agg(sum('Sales') as total_sales, mean('Returns') as avg_returns, count('Sales') as sales_count)
B. df.groupby('Store').agg(total_sales=('Sales', 'sum'), avg_returns=('Returns', 'mean'), sales_count=('Sales', 'count'))
C. df.groupby('Store').agg(total_sales='sum', avg_returns='mean', sales_count='count')
D. df.groupby('Store').agg({'total_sales': ('Sales', 'sum'), 'avg_returns': ('Returns', 'mean'), 'sales_count': ('Sales', 'count')})

Solution

  1. Step 1: Recall named aggregation syntax

    Use keyword arguments with new_name=(column, function) inside agg().
  2. Step 2: Evaluate each option

    df.groupby('Store').agg(total_sales=('Sales', 'sum'), avg_returns=('Returns', 'mean'), sales_count=('Sales', 'count')) correctly uses named aggregation syntax. df.groupby('Store').agg({'total_sales': ('Sales', 'sum'), 'avg_returns': ('Returns', 'mean'), 'sales_count': ('Sales', 'count')}) uses a dictionary but this is not valid for named aggregation. df.groupby('Store').agg(total_sales='sum', avg_returns='mean', sales_count='count') uses strings without specifying columns. df.groupby('Store').agg(sum('Sales') as total_sales, mean('Returns') as avg_returns, count('Sales') as sales_count) uses invalid syntax.
  3. Final Answer:

    df.groupby('Store').agg(total_sales=('Sales', 'sum'), avg_returns=('Returns', 'mean'), sales_count=('Sales', 'count')) -> Option B
  4. Quick Check:

    Named aggregation = keyword args with (col, func) tuples [OK]
Hint: Use new_name=(col, func) for multiple summaries [OK]
Common Mistakes:
  • Using dictionary instead of keyword arguments
  • Passing only function names without columns
  • Trying SQL-like syntax inside agg()
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