0
0
Pandasdata~20 mins

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

Choose your learning style9 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.