Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Single and multiple column grouping in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Master of Grouping
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ data_output
intermediate
2:00remaining
Output of single column grouping with aggregation
Given the following DataFrame, what is the output of grouping by the 'Category' column and calculating the sum of 'Sales'?
Data Analysis Python
import pandas as pd

data = {'Category': ['A', 'B', 'A', 'B', 'C'], 'Sales': [100, 200, 150, 300, 250]}
df = pd.DataFrame(data)
result = df.groupby('Category')['Sales'].sum()
print(result)
ACategory\nA 250\nB 500\nC 250\nName: Sales, dtype: int64
BCategory\nA 100\nB 200\nC 250\nName: Sales, dtype: int64
CCategory\nA 150\nB 300\nC 250\nName: Sales, dtype: int64
DCategory\nA 350\nB 500\nC 250\nName: Sales, dtype: int64
Attempts:
2 left
💡 Hint
Sum the 'Sales' values for each unique 'Category'.
❓ data_output
intermediate
2:00remaining
Output of multiple column grouping with mean aggregation
What is the output of grouping the DataFrame by 'Category' and 'Region' columns and calculating the mean of 'Sales'?
Data Analysis Python
import pandas as pd

data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'], 'Region': ['East', 'West', 'East', 'West', 'East', 'West'], 'Sales': [100, 150, 200, 300, 250, 350]}
df = pd.DataFrame(data)
result = df.groupby(['Category', 'Region'])['Sales'].mean()
print(result)
ACategory Region\nA East 100\n West 150\nB East 200\n West 300\nC East 250\n West 350\nName: Sales, dtype: int64
BCategory Region\nA East 125.0\n West 225.0\nB East 250.0\n West 325.0\nC East 300.0\n West 400.0\nName: Sales, dtype: float64
CCategory Region\nA East 100.0\n West 150.0\nB East 200.0\n West 300.0\nC East 250.0\n West 350.0\nName: Sales, dtype: float64
DCategory Region\nA East 150.0\n West 100.0\nB East 300.0\n West 200.0\nC East 350.0\n West 250.0\nName: Sales, dtype: float64
Attempts:
2 left
💡 Hint
Calculate the average sales for each combination of Category and Region.
🧠 Conceptual
advanced
2:00remaining
Understanding groupby object behavior
What happens if you try to access a column that was not included in the aggregation after grouping a DataFrame by a column?
Data Analysis Python
import pandas as pd

data = {'Category': ['A', 'B', 'A'], 'Sales': [100, 200, 150], 'Profit': [30, 50, 40]}
df = pd.DataFrame(data)
grouped = df.groupby('Category')['Sales'].sum()
print(grouped['Profit'])
AReturns the sum of 'Profit' for each category.
BRaises a KeyError because 'Profit' is not part of the grouped object.
CReturns the original 'Profit' column without grouping.
DReturns NaN values for 'Profit' since it was not aggregated.
Attempts:
2 left
💡 Hint
Check if the grouped object contains the 'Profit' column.
🔧 Debug
advanced
2:00remaining
Identify the error in multiple column grouping code
What error will this code raise when grouping by multiple columns and aggregating?
Data Analysis Python
import pandas as pd

data = {'Category': ['A', 'B', 'A'], 'Region': ['East', 'West', 'East'], 'Sales': [100, 200, 150]}
df = pd.DataFrame(data)
result = df.groupby('Category', 'Region')['Sales'].sum()
print(result)
AKeyError: 'Region' not found
BNo error, outputs grouped sums correctly
CSyntaxError: invalid syntax
DTypeError: groupby() takes 2 positional arguments but 3 were given
Attempts:
2 left
💡 Hint
Check the syntax of the groupby method arguments.
🚀 Application
expert
3:00remaining
Calculate total sales and average profit by category and region
Given the DataFrame below, which code snippet correctly groups by 'Category' and 'Region' to calculate total 'Sales' and average 'Profit'?
Data Analysis Python
import pandas as pd

data = {'Category': ['A', 'A', 'B', 'B', 'C', 'C'], 'Region': ['East', 'West', 'East', 'West', 'East', 'West'], 'Sales': [100, 150, 200, 300, 250, 350], 'Profit': [20, 30, 40, 50, 60, 70]}
df = pd.DataFrame(data)
A
result = df.groupby(['Category', 'Region']).agg({'Sales': 'sum', 'Profit': 'mean'})
print(result)
B
result = df.groupby('Category', 'Region').agg({'Sales': 'sum', 'Profit': 'mean'})
print(result)
C
result = df.groupby(['Category', 'Region'])[['Sales', 'Profit']].agg(['sum', 'mean'])
print(result)
D
result = df.groupby(['Category', 'Region']).agg({'Sales': 'mean', 'Profit': 'sum'})
print(result)
Attempts:
2 left
💡 Hint
Use a dictionary to specify different aggregation functions for each column.

Practice

(1/5)
1. What does the groupby() function do in data analysis with pandas?
easy
A. It groups data based on one or more columns to summarize it.
B. It sorts the data alphabetically.
C. It deletes duplicate rows from the data.
D. It changes the data type of columns.

Solution

  1. Step 1: Understand the purpose of grouping

    Grouping means collecting rows that share the same value in one or more columns.
  2. Step 2: Role of groupby() in pandas

    The groupby() function in pandas helps to split data into groups based on column values for aggregation or analysis.
  3. Final Answer:

    It groups data based on one or more columns to summarize it. -> Option A
  4. Quick Check:

    Grouping = Summarizing data by columns [OK]
Hint: Remember: groupby = group rows by column values [OK]
Common Mistakes:
  • Thinking groupby sorts data
  • Confusing groupby with removing duplicates
  • Assuming groupby changes data types
2. Which of the following is the correct syntax to group a pandas DataFrame df by two columns 'A' and 'B'?
easy
A. df.groupby(['A', 'B'])
B. df.groupby('A', 'B')
C. df.group_by(['A', 'B'])
D. df.groupby(['A' & 'B'])

Solution

  1. Step 1: Check pandas groupby syntax for multiple columns

    To group by multiple columns, pass a list of column names inside groupby: df.groupby(['A', 'B']).
  2. Step 2: Identify incorrect syntax options

    df.groupby('A', 'B') misses list brackets, df.group_by(['A', 'B']) uses wrong method name, df.groupby(['A' & 'B']) uses invalid operator inside list.
  3. Final Answer:

    df.groupby(['A', 'B']) -> Option A
  4. Quick Check:

    Multiple columns = list inside groupby [OK]
Hint: Use a list of columns inside groupby for multiple columns [OK]
Common Mistakes:
  • Passing columns as separate arguments instead of list
  • Using wrong method name like group_by
  • Using operators inside list instead of commas
3. Given the DataFrame df below:
   City  Sales  Quantity
0  NY    100    2
1  LA    200    3
2  NY    150    1
3  LA    100    4
4  NY    200    2

What is the output of df.groupby('City')['Sales'].sum()?
medium
A. City LA 400 NY 350 Name: Sales, dtype: int64
B. City LA 400 NY 450 Name: Sales, dtype: int64
C. City LA 300 NY 350 Name: Sales, dtype: int64
D. City LA 300 NY 450 Name: Sales, dtype: int64

Solution

  1. Step 1: Group data by 'City' and sum 'Sales'

    Group rows by City: LA rows have Sales 200 and 100, sum = 300; NY rows have Sales 100, 150, 200, sum = 450.
  2. Step 2: Write the resulting Series

    The result shows sums per city: LA 300, NY 450, with City as index and Sales as name.
  3. Final Answer:

    City LA 300 NY 450 Name: Sales, dtype: int64 -> Option D
  4. Quick Check:

    Sum Sales by City = LA:300, NY:450 [OK]
Hint: Add values per group to find sum quickly [OK]
Common Mistakes:
  • Adding wrong rows for each city
  • Mixing sum of Sales with Quantity
  • Confusing index and values in output
4. What is wrong with this code snippet?
df.groupby('Category', 'Type').mean()
medium
A. Category and Type columns must be numeric.
B. mean() cannot be used after groupby.
C. groupby expects a list for multiple columns, not separate arguments.
D. groupby requires column names as integers.

Solution

  1. Step 1: Check groupby syntax for multiple columns

    When grouping by multiple columns, pass a list: df.groupby(['Category', 'Type']). Passing separate arguments causes error.
  2. Step 2: Verify other options

    mean() is valid after groupby; columns can be non-numeric but mean applies only to numeric; column names are strings, not integers.
  3. Final Answer:

    groupby expects a list for multiple columns, not separate arguments. -> Option C
  4. Quick Check:

    Multiple columns need list in groupby [OK]
Hint: Use list brackets for multiple columns in groupby [OK]
Common Mistakes:
  • Passing multiple columns as separate arguments
  • Thinking mean() is invalid after groupby
  • Assuming column names must be integers
5. You have a sales DataFrame df with columns 'Region', 'Product', and 'Revenue'. You want to find the average revenue per region and product, but only for products with total revenue above 1000. Which code correctly achieves this?
hard
A. df.groupby(['Region', 'Product'])['Revenue'].mean()[df['Revenue'].sum() > 1000]
B. df.groupby(['Region', 'Product']).filter(lambda x: x['Revenue'].sum() > 1000).groupby(['Region', 'Product'])['Revenue'].mean()
C. df.groupby(['Region', 'Product'])['Revenue'].sum().mean() > 1000
D. df.groupby(['Region', 'Product'])['Revenue'].mean().filter(lambda x: x > 1000)

Solution

  1. Step 1: Filter groups with total revenue above 1000

    Use filter() with a lambda to keep groups where sum of Revenue > 1000.
  2. Step 2: Calculate mean revenue per filtered group

    After filtering, group again by Region and Product and calculate mean Revenue.
  3. Step 3: Analyze other options

    df.groupby(['Region', 'Product'])['Revenue'].mean()[df['Revenue'].sum() > 1000] uses total Revenue sum instead of per-group sum, returning all means or none; df.groupby(['Region', 'Product'])['Revenue'].sum().mean() > 1000 computes mean of sums, not per group; df.groupby(['Region', 'Product'])['Revenue'].mean().filter(lambda x: x > 1000) filters means > 1000, not sums.
  4. Final Answer:

    df.groupby(['Region', 'Product']).filter(lambda x: x['Revenue'].sum() > 1000).groupby(['Region', 'Product'])['Revenue'].mean() -> Option B
  5. Quick Check:

    Filter groups by sum, then compute mean [OK]
Hint: Use filter() to keep groups before aggregation [OK]
Common Mistakes:
  • Trying to filter after aggregation with mismatched indexes
  • Confusing mean of sums with sum of means
  • Filtering on mean instead of sum
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