Bird
Raised Fist0
Pandasdata~20 mins

Aggregation with agg() in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Aggregation Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of agg() with multiple functions
What is the output of the following code snippet using pandas agg() on a DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4],
    'B': [5, 6, 7, 8]
})
result = df.agg({'A': ['sum', 'max'], 'B': ['min', 'mean']})
print(result)
A
       A    B
sum  10.0  NaN
max   4.0  NaN
min   NaN  5.0
mean  NaN  6.5
B
5.6  NaN  naem
0.5  NaN   nim
NaN  0.4   xam
NaN  0.01  mus
B    A
C
       A    B
sum  10.0  26.0
max   4.0   8.0
min   1.0   5.0
mean  2.5   6.5
D{'A': {'sum': 10, 'max': 4}, 'B': {'min': 5, 'mean': 6.5}}
Attempts:
2 left
💡 Hint
Remember that agg() returns a DataFrame with the aggregation functions as the index and columns as the original DataFrame columns.
❓ data_output
intermediate
1:30remaining
Number of rows after groupby and agg
Given the DataFrame and code below, how many rows does the resulting DataFrame have?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Category': ['X', 'Y', 'X', 'Z', 'Y', 'Z'],
    'Value': [10, 20, 30, 40, 50, 60]
})
result = df.groupby('Category').agg({'Value': 'sum'})
print(len(result))
A3
B6
C1
D0
Attempts:
2 left
💡 Hint
Groupby groups rows by unique values in 'Category'. Count unique categories.
🔧 Debug
advanced
1:30remaining
Identify the error in agg() usage
What error does the following code raise when run?
Pandas
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3]})
result = df.agg({'A': 'sum', 'B': 'mean'})
ATypeError: unsupported operand type(s)
BKeyError: 'B'
CValueError: Function not found
DNo error, returns a DataFrame
Attempts:
2 left
💡 Hint
Check if all keys in the agg dictionary exist as columns in the DataFrame.
🚀 Application
advanced
2:00remaining
Using agg() with custom functions
Which option correctly uses agg() to compute the range (max - min) of column 'Scores' in the DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({'Scores': [88, 92, 79, 93, 85]})
Adf.agg({'Scores': lambda x: x.min() - x.max()})
Bdf.agg({'Scores': lambda x: sum(x)})
Cdf.agg({'Scores': lambda x: x.max() - x.min()})
Ddf.agg({'Scores': 'mean'})
Attempts:
2 left
💡 Hint
Range is max value minus min value.
🧠 Conceptual
expert
2:00remaining
Understanding agg() output shape with mixed aggregations
If you run agg() on a DataFrame with two columns, applying ['sum', 'mean'] to the first column and 'max' to the second column, what will be the shape of the resulting DataFrame?
AA DataFrame with 2 rows and 2 columns
BA DataFrame with 2 rows and 3 columns
CA Series with 3 elements
DA DataFrame with 3 rows and 2 columns
Attempts:
2 left
💡 Hint
Count total aggregation functions applied and number of columns.

Practice

(1/5)
1.

What does the agg() function do in pandas?

easy
A. It sorts the DataFrame rows by index.
B. It applies one or more aggregation functions to DataFrame columns.
C. It filters rows based on a condition.
D. It merges two DataFrames together.

Solution

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

    The agg() function is used to apply aggregation functions like sum, mean, count, etc., to DataFrame columns.
  2. Step 2: Compare with other options

    Sorting, filtering, and merging are done by other pandas functions, not agg().
  3. Final Answer:

    It applies one or more aggregation functions to DataFrame columns. -> Option B
  4. Quick Check:

    agg() = aggregation [OK]
Hint: Remember agg() means aggregate functions on columns [OK]
Common Mistakes:
  • Confusing agg() with sorting or filtering functions
  • Thinking agg() modifies row order
  • Assuming agg() merges DataFrames
2.

Which of the following is the correct syntax to apply agg() with multiple functions on a DataFrame df?

df.agg({'col1': ['sum', 'mean'], 'col2': ['min', 'max']})
easy
A. df.agg({'col1': ['sum', 'mean'], 'col2': ['min', 'max']})
B. df.aggregate(['sum', 'mean'], ['min', 'max'])
C. df.agg(['col1': 'sum', 'col2': 'min'])
D. df.agg({'sum', 'mean', 'min', 'max'})

Solution

  1. Step 1: Review correct agg() syntax

    The correct syntax uses a dictionary mapping column names to lists of functions: {'col1': ['sum', 'mean'], 'col2': ['min', 'max']}.
  2. Step 2: Check each option

    df.agg({'col1': ['sum', 'mean'], 'col2': ['min', 'max']}) matches the correct syntax. Options A, B, and D have syntax errors or wrong argument formats.
  3. Final Answer:

    df.agg({'col1': ['sum', 'mean'], 'col2': ['min', 'max']}) -> Option A
  4. Quick Check:

    Dictionary with column keys and function lists = df.agg({'col1': ['sum', 'mean'], 'col2': ['min', 'max']}) [OK]
Hint: Use dict with columns as keys and list of funcs as values [OK]
Common Mistakes:
  • Passing functions as separate arguments instead of dict
  • Using sets {} instead of dict for agg()
  • Incorrect list or dict syntax inside agg()
3.

Given the DataFrame:

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
result = df.agg({'A': ['sum', 'max'], 'B': ['sum', 'max']})
print(result)

What is the output?

medium
A. A B sum 6 15 max 3 6
B. A B sum 6 4 max 3 4
C. A B sum 6 5 max 3 6
D. A B sum 6 5 max 3 4

Solution

  1. Step 1: Calculate aggregation for column 'A'

    Sum of [1, 2, 3] is 6; max is 3.
  2. Step 2: Calculate aggregation for column 'B'

    Sum of [4, 5, 6] is 15; max is 6.
  3. Final Answer:

    A B sum 6 15 max 3 6 -> Option A
  4. Quick Check:

    Sum A=6, Max A=3, Sum B=15, Max B=6 [OK]
Hint: Apply each function only to specified columns [OK]
Common Mistakes:
  • Assuming max applies to column B
  • Mixing up min and max values
  • Confusing row and column labels in output
4.

What is wrong with this code snippet?

import pandas as pd
df = pd.DataFrame({'X': [10, 20], 'Y': [30, 40]})
result = df.agg({'X': 'sum', 'Y': ['mean', 'max']})
print(result)
medium
A. Error because 'agg()' requires all functions as strings.
B. Error because 'sum' should be in a list for column 'X'.
C. Error because 'agg()' cannot mix single and multiple functions.
D. No error; code runs and prints correct aggregation.

Solution

  1. Step 1: Check if mixing single and multiple functions is allowed

    In pandas, you can pass a single function as a string or multiple as a list per column in agg().
  2. Step 2: Verify syntax correctness

    Passing 'sum' as a string for 'X' and ['mean', 'max'] for 'Y' is valid syntax.
  3. Final Answer:

    No error; code runs and prints correct aggregation. -> Option D
  4. Quick Check:

    Single or list functions per column both allowed [OK]
Hint: Single function can be string; multiple must be list [OK]
Common Mistakes:
  • Thinking all functions must be lists
  • Assuming mixing single and list causes error
  • Confusing function names with strings vs objects
5.

You have a DataFrame df with columns 'Product', 'Sales', and 'Quantity'. You want to group by 'Product' and get the total sales, average quantity, and maximum sales per product. Which agg() call achieves this?

hard
A. df.groupby('Product').agg({'Sales': ['mean'], 'Quantity': ['sum', 'max']})
B. df.groupby('Product').agg({'Sales': 'mean', 'Quantity': ['sum', 'max']})
C. df.groupby('Product').agg({'Sales': ['sum', 'max'], 'Quantity': 'mean'})
D. df.groupby('Product').agg({'Product': ['sum'], 'Sales': 'max', 'Quantity': 'mean'})

Solution

  1. Step 1: Identify required aggregations per column

    We want total sales (sum), average quantity (mean), and maximum sales (max) grouped by product.
  2. Step 2: Match functions to columns

    For 'Sales', apply 'sum' and 'max'; for 'Quantity', apply 'mean'. Grouping is by 'Product'.
  3. Step 3: Check options

    df.groupby('Product').agg({'Sales': ['sum', 'max'], 'Quantity': 'mean'}) matches the requirements exactly. Others have wrong functions or columns.
  4. Final Answer:

    df.groupby('Product').agg({'Sales': ['sum', 'max'], 'Quantity': 'mean'}) -> Option C
  5. Quick Check:

    Group by Product, Sales sum & max, Quantity mean = df.groupby('Product').agg({'Sales': ['sum', 'max'], 'Quantity': 'mean'}) [OK]
Hint: Map each column to needed functions in a dict inside agg() [OK]
Common Mistakes:
  • Applying wrong functions to columns
  • Including grouping column in agg()
  • Mixing aggregation functions incorrectly
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