📖 Scenario: Imagine you work at a small bookstore. You have sales data for different book genres and want to find out the average sales for each genre. This helps you understand which types of books sell best.
🎯 Goal: You will create a pandas DataFrame with sales data, then use the split-apply-combine method to calculate the average sales per genre.
📋 What You'll Learn
Create a pandas DataFrame named sales_data with columns 'Genre' and 'Sales' using the exact data provided.
Create a variable named group_column and set it to the string 'Genre'.
Use the split-apply-combine method by grouping sales_data by group_column and calculating the mean sales for each genre, storing the result in average_sales.
Print the average_sales DataFrame to show the average sales per genre.
💡 Why This Matters
🌍 Real World
Bookstores and many businesses use the split-apply-combine method to analyze grouped data, like sales by category or customer segment.
💼 Career
Data analysts and data scientists often use pandas groupby operations to summarize and understand data quickly.
Progress0 / 4 steps
1
Create the sales data DataFrame
Create a pandas DataFrame called sales_data with two columns: 'Genre' and 'Sales'. Use this exact data: 'Genre' values are 'Fiction', 'Non-Fiction', 'Fiction', 'Science', 'Non-Fiction', 'Science'. Corresponding 'Sales' values are 100, 150, 200, 130, 170, 120. Import pandas as pd first.
Pandas
Hint
Use pd.DataFrame with a dictionary where keys are column names and values are lists of data.
2
Set the group column
Create a variable called group_column and set it to the string 'Genre'.
Pandas
Hint
Just assign the string 'Genre' to the variable group_column.
3
Calculate average sales per genre
Use the split-apply-combine method by grouping sales_data by group_column and calculating the mean of 'Sales'. Store the result in a variable called average_sales.
Pandas
Hint
Use sales_data.groupby(group_column)['Sales'].mean() to get average sales per genre.
4
Print the average sales
Print the average_sales variable to display the average sales per genre.
Pandas
Hint
Use print(average_sales) to show the result.
Practice
(1/5)
1. What is the main idea behind the split-apply-combine mental model in pandas?
easy
A. Create new columns, rename them, then delete old columns
B. Sort data, filter rows, then plot results
C. Split data into groups, apply a function to each group, then combine results
D. Load data, clean missing values, then save to file
Solution
Step 1: Understand the split step
The data is divided into groups based on some criteria using groupby().
Step 2: Apply and combine steps
A function is applied to each group separately, then the results are combined into a new DataFrame.
Final Answer:
Split data into groups, apply a function to each group, then combine results -> Option C
Confusing split-apply-combine with sorting or filtering
Thinking it only applies to plotting or saving files
Mixing up the order of steps
2. Which of the following is the correct syntax to group a DataFrame df by the column 'Category' and calculate the mean of each group?
easy
A. df.groupby('Category').mean()
B. df.mean().groupby('Category')
C. df.groupby.mean('Category')
D. df.groupby('Category').apply(mean)
Solution
Step 1: Identify correct groupby syntax
The correct way to group by a column is df.groupby('Category').
Step 2: Apply aggregation function
To get the mean of each group, use .mean() after grouping.
Final Answer:
df.groupby('Category').mean() -> Option A
Quick Check:
Groupby then mean = df.groupby('Category').mean() [OK]
Hint: Use df.groupby('col').mean() to get group means [OK]
Common Mistakes:
Calling mean before groupby
Using apply(mean) without importing mean function
Wrong method chaining order
3. Given the DataFrame df below:
Category Value
0 A 5
1 B 3
2 A 7
3 B 2
4 C 4
What is the output of df.groupby('Category').sum()?
medium
A. Category as column with sums: A=5, B=3, C=4
B. Error because sum() cannot be applied
C. Sum of all values ignoring groups: 21
D. Category as index with sums: A=12, B=5, C=4
Solution
Step 1: Group data by 'Category'
Rows are grouped by 'Category': A, B, and C groups.
Step 2: Sum values in each group
Sum values for A: 5+7=12, B: 3+2=5, C: 4.
Final Answer:
Category as index with sums: A=12, B=5, C=4 -> Option D
Quick Check:
Sum per group = A:12, B:5, C:4 [OK]
Hint: Sum values after groupby to get totals per group [OK]
Common Mistakes:
Summing all values ignoring groups
Expecting category as a column instead of index
Thinking sum() causes error
4. Consider this code snippet:
result = df.groupby('Type').agg({'Score': 'mean', 'Age': 'max'})
What is wrong if the code raises a KeyError?
medium
A. The aggregation functions 'mean' and 'max' are invalid
B. The DataFrame does not have a column named 'Type'
C. The groupby method cannot take a string argument
D. agg() requires a list, not a dictionary
Solution
Step 1: Understand KeyError cause
A KeyError usually means the column used for grouping does not exist in the DataFrame.
Step 2: Check groupby argument and agg usage
Using a string in groupby and a dictionary in agg is correct syntax.
Final Answer:
The DataFrame does not have a column named 'Type' -> Option B
Quick Check:
KeyError means missing column [OK]
Hint: Check column names before groupby to avoid KeyError [OK]
Common Mistakes:
Assuming aggregation functions are invalid
Thinking groupby can't take string columns
Misunderstanding agg() argument types
5. You have a DataFrame df with columns 'Team', 'Player', and 'Points'. You want to find the player with the highest points in each team. Which code correctly uses the split-apply-combine model to achieve this?
hard
A. df.groupby('Team').apply(lambda g: g[g['Points'] == g['Points'].max()])
B. df.groupby('Team')['Points'].max()
C. df.groupby('Player')['Points'].sum()
D. df.groupby('Team').mean()['Points']
Solution
Step 1: Understand the goal
We want the player with the highest points per team, not just the max points value.
Step 2: Use groupby and apply to filter rows
Using apply with a lambda filters each group to rows where 'Points' equals the group's max.
Step 3: Check other options
df.groupby('Team')['Points'].max() returns max points per team but not the player. df.groupby('Player')['Points'].sum() groups by player, not team. df.groupby('Team').mean()['Points'] returns mean points, not max player.
Final Answer:
df.groupby('Team').apply(lambda g: g[g['Points'] == g['Points'].max()]) -> Option A
Quick Check:
Use apply with filter to get max player per group [OK]
Hint: Use groupby + apply with filter to get max per group row [OK]
Common Mistakes:
Using max() alone returns only values, not rows
Grouping by wrong column
Using mean() instead of max()
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.