Bird
Raised Fist0
Pandasdata~20 mins

Why grouping data matters in Pandas - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Grouping Data Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of GroupBy Sum Aggregation
What is the output of this code that groups sales by product and sums the amounts?
Pandas
import pandas as pd

data = {'product': ['apple', 'banana', 'apple', 'banana', 'apple'],
        'amount': [10, 5, 15, 10, 5]}
df = pd.DataFrame(data)
result = df.groupby('product')['amount'].sum()
print(result)
A
product
apple     10
banana    5
Name: amount, dtype: int64
B
product
apple     15
banana    15
Name: amount, dtype: int64
C
product
apple     30
banana    25
Name: amount, dtype: int64
D
product
apple     30
banana    15
Name: amount, dtype: int64
Attempts:
2 left
💡 Hint
Sum all amounts for each product separately.
❓ data_output
intermediate
1:30remaining
Number of Groups Created by GroupBy
How many groups are created when grouping this DataFrame by the 'category' column?
Pandas
import pandas as pd

data = {'category': ['A', 'B', 'A', 'C', 'B', 'C', 'C'],
        'value': [1, 2, 3, 4, 5, 6, 7]}
df = pd.DataFrame(data)
groups = df.groupby('category')
print(len(groups))
A3
B7
C2
D4
Attempts:
2 left
💡 Hint
Count unique values in 'category'.
❓ visualization
advanced
2:30remaining
Visualizing Grouped Data with Mean Values
Which plot correctly shows the average score per class from the grouped data?
Pandas
import pandas as pd
import matplotlib.pyplot as plt

data = {'class': ['X', 'Y', 'X', 'Y', 'X'], 'score': [80, 90, 70, 85, 75]}
df = pd.DataFrame(data)
grouped = df.groupby('class')['score'].mean()

plt.bar(grouped.index, grouped.values)
plt.xlabel('Class')
plt.ylabel('Average Score')
plt.title('Average Score per Class')
plt.show()
AA line chart with points at X=80 and Y=90.
BA bar chart with two bars labeled X and Y, heights 75 and 87.5 respectively.
CA scatter plot with points for each individual score.
DA pie chart showing proportions of total scores per class.
Attempts:
2 left
💡 Hint
Mean scores are 75 for X and 87.5 for Y.
🔧 Debug
advanced
1:30remaining
Identify the Error in GroupBy Usage
What error does this code raise when grouping by a non-existent column?
Pandas
import pandas as pd

data = {'name': ['Anna', 'Bob'], 'age': [25, 30]}
df = pd.DataFrame(data)
result = df.groupby('salary').mean()
AKeyError: 'salary'
BTypeError: unhashable type: 'list'
CValueError: No numeric types to aggregate
DAttributeError: 'DataFrame' object has no attribute 'groupby'
Attempts:
2 left
💡 Hint
Check if the column exists in the DataFrame.
🚀 Application
expert
2:30remaining
Calculate Total Sales per Region and Month
Given sales data with 'region', 'month', and 'sales' columns, which code correctly groups by region and month and sums sales?
Pandas
import pandas as pd

data = {'region': ['North', 'South', 'North', 'South', 'North'],
        'month': ['Jan', 'Jan', 'Feb', 'Feb', 'Jan'],
        'sales': [100, 200, 150, 250, 50]}
df = pd.DataFrame(data)
Adf.groupby(['region', 'month']).sum()['sales']
Bdf.groupby('region', 'month')['sales'].sum()
Cdf.groupby(['region', 'month'])['sales'].sum()
Ddf.groupby('region')['month']['sales'].sum()
Attempts:
2 left
💡 Hint
Group by both columns using a list, then select 'sales' to sum.

Practice

(1/5)
1. Why do we use grouping in pandas when working with data?
easy
A. To organize data into smaller parts based on shared values
B. To delete rows with missing values
C. To change the data type of columns
D. To sort data alphabetically

Solution

  1. Step 1: Understand the purpose of grouping

    Grouping divides data into parts where rows share common values in one or more columns.
  2. Step 2: Identify why grouping is useful

    This helps calculate summaries like totals or averages for each group, making data easier to analyze.
  3. Final Answer:

    To organize data into smaller parts based on shared values -> Option A
  4. Quick Check:

    Grouping = Organizing data by shared values [OK]
Hint: Grouping splits data by shared values for easy summaries [OK]
Common Mistakes:
  • Confusing grouping with sorting
  • Thinking grouping deletes data
  • Believing grouping changes data types
2. Which of the following is the correct syntax to group a pandas DataFrame df by the column 'Category'?
easy
A. df.groupby('Category')
B. df.group_by('Category')
C. df.group('Category')
D. df.groupby_by('Category')

Solution

  1. Step 1: Recall pandas grouping syntax

    The correct method to group data is groupby without underscores or extra words.
  2. Step 2: Match the correct method call

    Only df.groupby('Category') matches pandas syntax exactly.
  3. Final Answer:

    df.groupby('Category') -> Option A
  4. Quick Check:

    Correct method is groupby() [OK]
Hint: Use df.groupby('column') to group data correctly [OK]
Common Mistakes:
  • Using underscores incorrectly in method name
  • Adding extra words like 'by' twice
  • Using group() instead of groupby()
3. Given the DataFrame df below:
import pandas as pd
data = {'Team': ['A', 'A', 'B', 'B', 'C'], 'Points': [10, 15, 10, 5, 20]}
df = pd.DataFrame(data)
result = df.groupby('Team').sum()

What is the output of result?
medium
A. Team as column with Points averaged per team
B. Error because sum() cannot be used after groupby
C. Original DataFrame unchanged
D. Team as index with Points summed per team: A=25, B=15, C=20

Solution

  1. Step 1: Group data by 'Team'

    The groupby('Team') groups rows by team names: A, B, and C.
  2. Step 2: Sum the 'Points' for each group

    Points for A: 10+15=25, B: 10+5=15, C: 20.
  3. Final Answer:

    Team as index with Points summed per team: A=25, B=15, C=20 -> Option D
  4. Quick Check:

    Sum points per team = 25, 15, 20 [OK]
Hint: Sum after groupby adds values per group [OK]
Common Mistakes:
  • Expecting average instead of sum
  • Thinking groupby returns original data
  • Believing sum() causes error after groupby
4. What is wrong with this code snippet?
import pandas as pd
data = {'City': ['X', 'Y', 'X', 'Z'], 'Sales': [100, 200, 150, 300]}
df = pd.DataFrame(data)
result = df.group('City').mean()

Choose the best explanation.
medium
A. The DataFrame is missing a column for grouping
B. The method group does not exist; should be groupby
C. The mean() function cannot be used after grouping
D. The data dictionary is incorrectly formatted

Solution

  1. Step 1: Check the grouping method name

    The code uses df.group('City'), but pandas requires groupby.
  2. Step 2: Confirm mean() is valid after grouping

    mean() works correctly after groupby, so no error there.
  3. Final Answer:

    The method group does not exist; should be groupby -> Option B
  4. Quick Check:

    Use groupby(), not group() [OK]
Hint: Use groupby(), not group(), to avoid errors [OK]
Common Mistakes:
  • Using group() instead of groupby()
  • Thinking mean() is invalid after grouping
  • Assuming data format is wrong
5. You have a sales DataFrame df with columns 'Store', 'Product', and 'Revenue'. You want to find the total revenue per store but only for products with revenue above 100. Which pandas code correctly does this?
hard
A. df.groupby('Store').filter(lambda x: x['Revenue'] > 100).sum()
B. df.groupby('Store')['Revenue'].sum()[df['Revenue'] > 100]
C. df[df['Revenue'] > 100].groupby('Store')['Revenue'].sum()
D. df.groupby('Product')['Revenue'].sum().loc[df['Revenue'] > 100]

Solution

  1. Step 1: Filter rows where Revenue > 100

    Use df[df['Revenue'] > 100] to keep only rows with revenue above 100.
  2. Step 2: Group filtered data by 'Store' and sum 'Revenue'

    Then group by 'Store' and sum the 'Revenue' column to get totals per store.
  3. Final Answer:

    df[df['Revenue'] > 100].groupby('Store')['Revenue'].sum() -> Option C
  4. Quick Check:

    Filter first, then group and sum [OK]
Hint: Filter rows first, then group and sum [OK]
Common Mistakes:
  • Grouping before filtering, causing wrong sums
  • Filtering on grouped sums incorrectly
  • Using filter() without returning boolean mask
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