Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Aggregation-based features in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Aggregation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of group aggregation with multiple functions
What is the output of the following code snippet that groups data by 'Category' and calculates the mean and max of 'Value'?
Data Analysis Python
import pandas as pd

data = pd.DataFrame({
    'Category': ['A', 'A', 'B', 'B', 'C'],
    'Value': [10, 20, 10, 30, 40]
})

result = data.groupby('Category')['Value'].agg(['mean', 'max']).reset_index()
print(result)
A[{'Category': 'A', 'mean': 15.0, 'max': 20}, {'Category': 'B', 'mean': 20.0, 'max': 30}, {'Category': 'C', 'mean': 40.0, 'max': 40}]
B[{'Category': 'A', 'mean': 10.0, 'max': 20}, {'Category': 'B', 'mean': 20.0, 'max': 30}, {'Category': 'C', 'mean': 40.0, 'max': 40}]
C[{'Category': 'A', 'mean': 15.0, 'max': 10}, {'Category': 'B', 'mean': 20.0, 'max': 30}, {'Category': 'C', 'mean': 40.0, 'max': 40}]
D[{'Category': 'A', 'mean': 15.0, 'max': 20}, {'Category': 'B', 'mean': 20.0, 'max': 10}, {'Category': 'C', 'mean': 40.0, 'max': 40}]
Attempts:
2 left
💡 Hint
Remember that mean is the average and max is the highest value in each group.
❓ data_output
intermediate
2:00remaining
Number of unique users per product
Given a DataFrame with user purchases, what is the number of unique users who bought each product?
Data Analysis Python
import pandas as pd

data = pd.DataFrame({
    'User': ['Alice', 'Bob', 'Alice', 'David', 'Bob', 'Eve'],
    'Product': ['X', 'X', 'Y', 'Y', 'X', 'Z']
})

result = data.groupby('Product')['User'].nunique().reset_index(name='UniqueUsers')
print(result)
A[{'Product': 'X', 'UniqueUsers': 2}, {'Product': 'Y', 'UniqueUsers': 3}, {'Product': 'Z', 'UniqueUsers': 1}]
B[{'Product': 'X', 'UniqueUsers': 3}, {'Product': 'Y', 'UniqueUsers': 2}, {'Product': 'Z', 'UniqueUsers': 1}]
C[{'Product': 'X', 'UniqueUsers': 2}, {'Product': 'Y', 'UniqueUsers': 2}, {'Product': 'Z', 'UniqueUsers': 1}]
D[{'Product': 'X', 'UniqueUsers': 3}, {'Product': 'Y', 'UniqueUsers': 3}, {'Product': 'Z', 'UniqueUsers': 1}]
Attempts:
2 left
💡 Hint
Count distinct users per product.
❓ visualization
advanced
2:30remaining
Visualizing average sales per region
Which plot correctly shows the average sales per region from the given data?
Data Analysis Python
import pandas as pd
import matplotlib.pyplot as plt

data = pd.DataFrame({
    'Region': ['North', 'South', 'East', 'West', 'North', 'South'],
    'Sales': [100, 150, 200, 130, 120, 170]
})
avg_sales = data.groupby('Region')['Sales'].mean().reset_index()

plt.bar(avg_sales['Region'], avg_sales['Sales'])
plt.title('Average Sales per Region')
plt.xlabel('Region')
plt.ylabel('Average Sales')
plt.show()
ABar chart with regions on x-axis and average sales on y-axis, bars heights: North=110, South=160, East=200, West=130
BLine chart with regions on x-axis and average sales on y-axis, points: North=110, South=160, East=200, West=130
CPie chart showing percentage sales per region with values: North=220, South=320, East=200, West=130
DScatter plot with sales values plotted against region names
Attempts:
2 left
💡 Hint
Look for a bar chart showing average values per category.
🔧 Debug
advanced
2:00remaining
Identify the error in aggregation code
What error will the following code raise when executed?
Data Analysis Python
import pandas as pd

data = pd.DataFrame({
    'Category': ['A', 'B', 'A'],
    'Value': [10, 20, 30]
})

result = data.groupby('Category')['Value'].agg('sum', 'mean')
print(result)
ANo error, outputs sum and mean aggregation
BTypeError: agg() takes from 1 to 2 positional arguments but 3 were given
CKeyError: 'mean'
DValueError: Function names must be passed as a list or tuple
Attempts:
2 left
💡 Hint
Check how multiple aggregation functions are passed to agg().
🚀 Application
expert
3:00remaining
Calculate weighted average feature per group
You have a DataFrame with 'Group', 'Value', and 'Weight' columns. Which code correctly calculates the weighted average of 'Value' per 'Group' using 'Weight' as weights?
Data Analysis Python
import pandas as pd

data = pd.DataFrame({
    'Group': ['X', 'X', 'Y', 'Y', 'Y'],
    'Value': [10, 20, 30, 40, 50],
    'Weight': [1, 3, 2, 1, 1]
})
Adata.groupby('Group').agg({'Value': 'mean'}).reset_index()
Bdata.groupby('Group').apply(lambda x: x['Value'].mean() * x['Weight'].mean()).reset_index(name='WeightedAvg')
Cdata.groupby('Group').agg({'Value': lambda x: (x * data['Weight']).sum() / data['Weight'].sum()}).reset_index()
Ddata.groupby('Group').apply(lambda x: (x['Value'] * x['Weight']).sum() / x['Weight'].sum()).reset_index(name='WeightedAvg')
Attempts:
2 left
💡 Hint
Weighted average is sum of value*weight divided by sum of weights per group.

Practice

(1/5)
1. What is the main purpose of aggregation-based features in data analysis?
easy
A. To summarize data by groups using functions like sum or mean
B. To visualize data using charts and graphs
C. To clean missing values from the dataset
D. To split data into training and testing sets

Solution

  1. Step 1: Understand aggregation-based features

    Aggregation-based features summarize data by groups using functions like sum, mean, or count.
  2. Step 2: Compare with other options

    Visualization, cleaning, and splitting data are different tasks not related to aggregation features.
  3. Final Answer:

    To summarize data by groups using functions like sum or mean -> Option A
  4. Quick Check:

    Aggregation = summary by groups [OK]
Hint: Aggregation means grouping and summarizing data [OK]
Common Mistakes:
  • Confusing aggregation with visualization
  • Thinking aggregation cleans data
  • Mixing aggregation with data splitting
2. Which of the following is the correct syntax to calculate the mean of column 'sales' grouped by 'region' in pandas?
easy
A. df.mean('sales').groupby('region')
B. df['sales'].groupby('region').mean()
C. df.groupby('region')['sales'].mean()
D. df.groupby('sales')['region'].mean()

Solution

  1. Step 1: Identify correct groupby syntax

    The correct syntax groups by 'region' then selects 'sales' column and applies mean: df.groupby('region')['sales'].mean()
  2. Step 2: Check incorrect options

    df.mean('sales').groupby('region') reverses order, df['sales'].groupby('region').mean() tries to group on a column series, df.groupby('sales')['region'].mean() groups by 'sales' instead of 'region'.
  3. Final Answer:

    df.groupby('region')['sales'].mean() -> Option C
  4. Quick Check:

    Group by region, then mean sales [OK]
Hint: Use df.groupby('col')['col2'].agg_func() [OK]
Common Mistakes:
  • Calling mean before groupby
  • Grouping on wrong column
  • Applying groupby on a Series instead of DataFrame
3. Given the DataFrame:
import pandas as pd
data = {'team': ['A', 'A', 'B', 'B', 'B'], 'points': [10, 15, 10, 5, 20]}
df = pd.DataFrame(data)
result = df.groupby('team').agg({'points': 'sum'})
print(result)

What is the output?
medium
A. team\nA 25\nB 10
B. team\nA 10\nB 20
C. team\nA 15\nB 10
D. team\nA 25\nB 35

Solution

  1. Step 1: Group data by 'team'

    Teams are 'A' and 'B'. 'A' has points 10 and 15, 'B' has 10, 5, and 20.
  2. Step 2: Sum points per team

    Sum for 'A' = 10 + 15 = 25; Sum for 'B' = 10 + 5 + 20 = 35.
  3. Final Answer:

    team A 25 B 35 -> Option D
  4. Quick Check:

    Sum points by team = 25 and 35 [OK]
Hint: Sum points after groupby to get totals per team [OK]
Common Mistakes:
  • Adding only first value per group
  • Confusing sum with mean
  • Misreading group labels
4. What is wrong with this code snippet to get the average 'score' per 'class' in pandas?
df.groupby('class').score.agg('average')
medium
A. The groupby column 'class' is misspelled
B. The aggregation function name 'average' is invalid; should be 'mean'
C. The code should use double brackets: df.groupby(['class'])
D. The code is correct and will run without error

Solution

  1. Step 1: Check aggregation function name

    'average' is not a valid pandas aggregation function; the correct function for average is 'mean'.
  2. Step 2: Verify other parts

    Grouping by 'class' and accessing 'score' column is correct syntax; double brackets are optional here.
  3. Final Answer:

    The aggregation function name 'average' is invalid; should be 'mean' -> Option B
  4. Quick Check:

    Use 'mean' not 'average' for average calculation [OK]
Hint: Use 'mean' for average in agg() [OK]
Common Mistakes:
  • Using 'average' instead of 'mean'
  • Thinking double brackets are mandatory
  • Assuming code runs without error
5. You have a sales DataFrame with columns 'store', 'product', and 'revenue'. You want to create a new feature showing the average revenue per store and product combined. Which pandas code correctly creates this aggregation-based feature and adds it as a new column 'avg_rev' to the original DataFrame?
hard
A. df['avg_rev'] = df.groupby(['store', 'product'])['revenue'].transform('mean')
B. df['avg_rev'] = df.groupby('store')['revenue'].mean()
C. df['avg_rev'] = df.groupby('product')['revenue'].sum()
D. df['avg_rev'] = df.groupby(['store', 'product']).agg({'revenue': 'mean'})

Solution

  1. Step 1: Understand the goal

    We want average revenue per store and product, and add it as a new column matching original rows.
  2. Step 2: Use groupby with transform

    Using groupby on ['store', 'product'] and transform('mean') returns a Series aligned with original DataFrame, perfect for new column.
  3. Step 3: Check other options

    df['avg_rev'] = df.groupby('store')['revenue'].mean() groups only by store, not product; df['avg_rev'] = df.groupby('product')['revenue'].sum() sums revenue, not average; df['avg_rev'] = df.groupby(['store', 'product']).agg({'revenue': 'mean'}) returns a DataFrame, not a Series aligned for assignment.
  4. Final Answer:

    df['avg_rev'] = df.groupby(['store', 'product'])['revenue'].transform('mean') -> Option A
  5. Quick Check:

    Use transform to add group average as new column [OK]
Hint: Use transform for group stats as new column [OK]
Common Mistakes:
  • Using agg() which returns DataFrame, not Series
  • Grouping by only one column instead of both
  • Using sum instead of mean
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