📖 Scenario: You work at a small bookstore. You have sales data for different books sold on different days. You want to find out how many books were sold in total for each book title.
🎯 Goal: Build a simple program that groups sales data by book title and sums the number of books sold for each title.
📋 What You'll Learn
Create a dictionary with book titles as keys and number of books sold as values for each sale.
Create a list of dictionaries representing sales records with keys 'title' and 'copies_sold'.
Use a variable to hold the sales data list.
Use pandas to convert the sales data into a DataFrame.
Group the DataFrame by book title and sum the copies sold.
Print the grouped and summed result.
💡 Why This Matters
🌍 Real World
Bookstores and many businesses track sales data and group it by product to see which items sell best.
💼 Career
Data analysts and scientists often group data to summarize and find insights from large datasets.
Progress0 / 4 steps
1
Create sales data list
Create a list called sales_data with these exact dictionaries: {'title': 'Python Basics', 'copies_sold': 5}, {'title': 'Data Science 101', 'copies_sold': 3}, {'title': 'Python Basics', 'copies_sold': 2}, {'title': 'Machine Learning', 'copies_sold': 4}
Pandas
Hint
Use a list with dictionaries. Each dictionary has keys 'title' and 'copies_sold' with the exact values given.
2
Import pandas and create DataFrame
Import the pandas library as pd. Then create a DataFrame called df from the sales_data list.
Pandas
Hint
Use import pandas as pd and then pd.DataFrame() with sales_data.
3
Group by title and sum copies sold
Create a variable called grouped_sales that groups df by the 'title' column and sums the 'copies_sold' for each group.
Pandas
Hint
Use df.groupby('title')['copies_sold'].sum() to get total copies sold per title.
4
Print the grouped sales result
Print the grouped_sales variable to show total copies sold for each book title.
Pandas
Hint
Use print(grouped_sales) to display the result.
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
Step 1: Understand the purpose of grouping
Grouping divides data into parts where rows share common values in one or more columns.
Step 2: Identify why grouping is useful
This helps calculate summaries like totals or averages for each group, making data easier to analyze.
Final Answer:
To organize data into smaller parts based on shared values -> Option A
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
Step 1: Recall pandas grouping syntax
The correct method to group data is groupby without underscores or extra words.
Step 2: Match the correct method call
Only df.groupby('Category') matches pandas syntax exactly.
Final Answer:
df.groupby('Category') -> Option A
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
Step 1: Group data by 'Team'
The groupby('Team') groups rows by team names: A, B, and C.
Step 2: Sum the 'Points' for each group
Points for A: 10+15=25, B: 10+5=15, C: 20.
Final Answer:
Team as index with Points summed per team: A=25, B=15, C=20 -> Option D
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
Step 1: Check the grouping method name
The code uses df.group('City'), but pandas requires groupby.
Step 2: Confirm mean() is valid after grouping
mean() works correctly after groupby, so no error there.
Final Answer:
The method group does not exist; should be groupby -> Option B
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
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'
Then group by 'Store' and sum the 'Revenue' column to get totals per store.
Final Answer:
df[df['Revenue'] > 100].groupby('Store')['Revenue'].sum() -> Option C
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 unknownstrongwhile earning +1 Grip toward your certificate.