📖 Scenario: You work in a small bookstore. You have sales data for different book genres and the number of books sold each day. You want to analyze this data to find out the total books sold per genre and also find the difference between the highest and lowest sales for each genre.
🎯 Goal: Build a program that groups the sales data by book genre and applies a custom function to calculate the sales range (difference between max and min sales) for each genre.
📋 What You'll Learn
Create a pandas DataFrame with sales data for book genres and daily sales.
Define a custom function to calculate the range of sales (max - min).
Use groupby on the genre column and apply the custom function.
Print the resulting DataFrame showing total sales and sales range per genre.
💡 Why This Matters
🌍 Real World
Bookstores and retail stores often analyze sales data by category to understand performance and stock needs.
💼 Career
Data analysts and data scientists use grouping and custom functions to summarize and extract insights from sales and business data.
Progress0 / 4 steps
1
Create the sales data DataFrame
Create a pandas DataFrame called sales_data with two columns: 'Genre' and 'Sales'. Use these exact rows: 'Fiction', 10, 'Fiction', 15, 'Non-Fiction', 8, 'Non-Fiction', 12, 'Science', 5, 'Science', 7.
Pandas
Hint
Use pd.DataFrame with a dictionary where keys are column names and values are lists of data.
2
Define a custom function to calculate sales range
Define a function called sales_range that takes a pandas Series called group and returns the difference between the maximum and minimum values in group.
Pandas
Hint
Use group.max() and group.min() to find the highest and lowest sales.
3
Group by Genre and apply custom function
Use groupby on sales_data by the 'Genre' column. Calculate the total sales per genre using sum(). Then apply the sales_range function to the 'Sales' column for each genre. Store the total sales in total_sales and the sales range in range_sales.
Pandas
Hint
Use groupby('Genre')['Sales'] then sum() and apply(sales_range).
4
Print the total sales and sales range per genre
Print the total_sales and range_sales Series to display the total books sold and the sales range for each genre.
Pandas
Hint
Use two print() statements to show total_sales and range_sales.
Practice
(1/5)
1. What does the groupby function in pandas primarily do?
easy
A. It splits data into groups based on column values for separate analysis.
B. It sorts the entire DataFrame by column values.
C. It deletes duplicate rows from the DataFrame.
D. It merges two DataFrames based on a key column.
Solution
Step 1: Understand the purpose of groupby
The groupby function divides data into groups based on unique values in one or more columns.
Step 2: Recognize the use of groups
After grouping, you can apply functions to each group separately for analysis or aggregation.
Final Answer:
It splits data into groups based on column values for separate analysis. -> Option A
Quick Check:
Group data = split by column values [OK]
Hint: GroupBy splits data into parts by column values [OK]
Common Mistakes:
Confusing groupby with sorting
Thinking groupby deletes duplicates
Mixing groupby with merge operations
2. Which of the following is the correct syntax to apply a custom function my_func to each group after grouping by column 'Category' in a DataFrame df?
easy
A. df.groupby('Category').apply(my_func)
B. df.apply.groupby('Category')(my_func)
C. df.groupby('Category').my_func()
D. df.group_by('Category').apply(my_func)
Solution
Step 1: Recall pandas groupby syntax
The correct method to group by a column is df.groupby('ColumnName').
Step 2: Apply a custom function to groups
Use .apply(function) after grouping to run the function on each group.
Hint: Use groupby('col').apply(func) to run custom function [OK]
Common Mistakes:
Using wrong method name like group_by
Calling function directly on groupby object
Misplacing apply before groupby
3. Given the DataFrame df below:
import pandas as pd
data = {'Team': ['A', 'A', 'B', 'B', 'C'], 'Points': [10, 15, 10, 20, 30]}
df = pd.DataFrame(data)
# Custom function to get range of points in group
def point_range(x):
return x.max() - x.min()
result = df.groupby('Team')['Points'].apply(point_range).to_dict()
What is the value of result?
medium
A. {'A': 10, 'B': 10, 'C': 0}
B. {'A': 25, 'B': 30, 'C': 30}
C. {'A': 5, 'B': 10, 'C': 0}
D. {'A': 15, 'B': 20, 'C': 30}
Solution
Step 1: Group points by 'Team'
Teams: A has points [10, 15], B has [10, 20], C has [30].
Step 2: Calculate range (max - min) for each group
Range = max - min per group = {'A': 5, 'B': 10, 'C': 0} [OK]
Hint: Calculate max-min per group for range [OK]
Common Mistakes:
Confusing sum with range
Forgetting single value group range is zero
Mixing keys and values in result
4. Consider this code snippet:
import pandas as pd
data = {'Category': ['X', 'X', 'Y'], 'Value': [1, 2, 3]}
df = pd.DataFrame(data)
# Custom function to sum values
def sum_values(x):
return x.sum
result = df.groupby('Category')['Value'].apply(sum_values)
What is the issue with this code?
medium
A. The apply method cannot be used with custom functions.
B. The groupby syntax is incorrect; it should be groupby(['Category']).
C. The DataFrame is missing a required index column.
D. The function sum_values returns the method, not the sum result.
Solution
Step 1: Check the custom function definition
The function returns x.sum which is a method, not called (missing parentheses).
Step 2: Understand the effect on apply
Returning the method itself causes the result to be a method object, not the sum value.
Final Answer:
The function sum_values returns the method, not the sum result. -> Option D
Quick Check:
Missing () calls method, not result [OK]
Hint: Call sum() with parentheses to get result [OK]
Common Mistakes:
Forgetting parentheses on sum()
Thinking groupby syntax is wrong here
Believing apply can't use custom functions
5. You have a DataFrame df with columns 'Store', 'Product', and 'Sales'. You want to find the difference between the highest and lowest sales per store, but only for products with sales above 100. Which approach correctly uses groupby with a custom function to achieve this?
hard
A. df.groupby('Store')['Sales'].apply(lambda x: x[x > 100].max() - x[x > 100].min())
B. All of the above produce the same correct result.
C. df.groupby('Store').apply(lambda g: g[g['Sales'] > 100]['Sales'].max() - g[g['Sales'] > 100]['Sales'].min())
D. df[df['Sales'] > 100].groupby('Store')['Sales'].apply(lambda x: x.max() - x.min())
Solution
Step 1: Understand filtering sales above 100
One approach filters inside the apply lambda on each store's sales series. Another filters the DataFrame before grouping. The third filters inside the group apply on the subgroup DataFrame.
Step 2: Check if all approaches calculate max-min correctly
All three methods correctly compute the difference of max and min sales above 100 per store.
Step 3: Confirm equivalence of results
Filtering before or inside groupby leads to the same final result for this case.
Final Answer:
All of the above produce the same correct result. -> Option B
Quick Check:
Filtering + groupby + custom function = all correct [OK]
Hint: Filter before or inside groupby; both work [OK]
Common Mistakes:
Filtering after groupby without apply
Not filtering sales > 100 properly
Assuming only one method works
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.