📖 Scenario: Imagine you run a small store. You have a list of sales with the product name and the amount sold. You want to find out how much money you made from each product category.
🎯 Goal: You will create a dictionary of sales data, set a category filter, use a loop to sum sales by category, and finally print the total sales per category.
📋 What You'll Learn
Create a dictionary called sales with product names as keys and sales amounts as values
Create a variable called category to select a product category
Use a for loop with variables product and amount to iterate over sales.items()
Sum the sales amounts only for products in the selected category
Print the total sales amount for the selected category
💡 Why This Matters
🌍 Real World
Stores and businesses often need to see total sales by product category to understand which groups sell best.
💼 Career
Data analysts use grouping and summarizing techniques to create reports and insights from sales or customer data.
Progress0 / 4 steps
1
Create the sales data dictionary
Create a dictionary called sales with these exact entries: 'apple': 30, 'banana': 15, 'carrot': 10, 'broccoli': 20, 'orange': 25
Data Analysis Python
Hint
Use curly braces {} to create a dictionary with product names as keys and numbers as values.
2
Set the product category to sum
Create a variable called category and set it to the string 'fruit'
Data Analysis Python
Hint
Just assign the string 'fruit' to the variable category.
3
Sum sales for the selected category
Create a variable called total_sales and set it to 0. Then use a for loop with variables product and amount to iterate over sales.items(). Inside the loop, add amount to total_sales only if product is one of 'apple', 'banana', or 'orange' (these are fruits).
Data Analysis Python
Hint
Use total_sales = 0 before the loop. Then check if product is in the list of fruits before adding amount.
4
Print the total sales for the category
Write a print statement to display the text 'Total sales for fruit:' followed by the value of total_sales
Data Analysis Python
Hint
Use print('Total sales for fruit:', total_sales) to show the result.
Practice
(1/5)
1. What is the main purpose of using groupby in data analysis?
easy
A. To merge two datasets into one
B. To sort data in ascending order
C. To delete duplicate rows from data
D. To split data into groups based on categories and summarize each group
Solution
Step 1: Understand what groupby does
groupby splits data into groups based on category values, like grouping sales by region.
Step 2: Recognize the purpose of summarizing groups
After grouping, we apply summary functions like sum or mean to each group to get useful insights.
Final Answer:
To split data into groups based on categories and summarize each group -> Option D
Quick Check:
Groupby = split + summarize [OK]
Hint: Groupby = split data by category, then summarize [OK]
Common Mistakes:
Thinking groupby sorts data
Confusing groupby with merging datasets
Believing groupby deletes duplicates
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.group_by('Category').mean()
C. df.groupby('Category').average()
D. df.group('Category').mean()
Solution
Step 1: Identify the correct method name
The correct method to group data is groupby, not group_by or group.
Step 2: Use the correct aggregation function
The function to calculate average is mean(), not average().
Final Answer:
df.groupby('Category').mean() -> Option A
Quick Check:
Correct syntax = groupby + mean() [OK]
Hint: Use df.groupby('col').mean() for average by group [OK]
Common Mistakes:
Using wrong method name like group_by
Using average() instead of mean()
Missing parentheses after mean
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\nA 12\nB 3\nC 4
B. Category\nA 7\nB 5\nC 4
C. Category\nA 12\nB 5\nC 4
D. Category\nA 5\nB 2\nC 4
Solution
Step 1: Group rows by 'Category'
Group A has values 5 and 7, B has 3 and 2, C has 4.
Step 2: Sum values in each group
Sum for A = 5 + 7 = 12, B = 3 + 2 = 5, C = 4.
Final Answer:
Category
A 12
B 5
C 4 -> Option C
Quick Check:
Sum per group = 12, 5, 4 [OK]
Hint: Add values within each category group [OK]
Common Mistakes:
Adding only first value per group
Mixing sums between groups
Ignoring group labels in output
4. What is wrong with this code snippet?
df.groupby('Category').sum
It is intended to sum values by category.
medium
A. Missing parentheses after sum to call the function
B. Wrong method name; should be summarize()
C. groupby should be group_by
D. sum cannot be used with groupby
Solution
Step 1: Check method usage
sum is a method and needs parentheses to execute, like sum().
Step 2: Confirm other parts are correct
groupby is correct, and sum() is valid aggregation.
Final Answer:
Missing parentheses after sum to call the function -> Option A
Quick Check:
Method call needs () [OK]
Hint: Add () after sum to execute it [OK]
Common Mistakes:
Forgetting parentheses on methods
Using wrong method names
Changing groupby to group_by
5. You have sales data with columns 'Store', 'Product', and 'Revenue'. You want to find the total revenue per store, but only for products with revenue above 100. Which code correctly does this?
hard
A. df.groupby('Store')['Revenue'].sum()[df['Revenue'] > 100]
B. df[df['Revenue'] > 100].groupby('Store')['Revenue'].sum()
C. df.groupby('Store').sum(df['Revenue'] > 100)
D. df.groupby('Store')['Revenue'].filter(lambda x: x > 100).sum()
Solution
Step 1: Filter rows where Revenue > 100
Use df[df['Revenue'] > 100] to keep only rows with revenue above 100.
Step 2: Group filtered data by 'Store' and sum 'Revenue'
Apply groupby('Store')['Revenue'].sum() to get total revenue per store for filtered products.
Final Answer:
df[df['Revenue'] > 100].groupby('Store')['Revenue'].sum() -> Option B
Quick Check:
Filter first, then group and sum [OK]
Hint: Filter data before groupby to summarize conditionally [OK]
Common Mistakes:
Filtering after groupby which causes errors
Using filter() incorrectly on groupby object
Passing condition inside sum()
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.