0
0
Pandasdata~30 mins

Iterating over groups in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Iterating over groups
📖 Scenario: You work in a small bakery that tracks daily sales of different types of bread. You have a table of sales data with the bread type and the number of loaves sold each day. You want to analyze the sales by bread type.
🎯 Goal: Build a program that groups the sales data by bread type and iterates over each group to see the sales details.
📋 What You'll Learn
Create a pandas DataFrame with bread sales data
Create a grouping variable using groupby on the bread type
Use a for loop to iterate over the groups
Print the group name and the group data
💡 Why This Matters
🌍 Real World
Grouping data is common in sales, finance, and many fields to analyze subsets of data separately.
💼 Career
Data analysts and scientists often group data to summarize and understand patterns in business data.
Progress0 / 4 steps
1
Create the sales DataFrame
Import pandas as pd and create a DataFrame called sales with these exact columns and values: 'Bread' with values ['Sourdough', 'Baguette', 'Sourdough', 'Baguette', 'Rye'] and 'Loaves' with values [10, 15, 7, 20, 5].
Pandas
Need a hint?

Use pd.DataFrame with a dictionary to create the table.

2
Group the sales by bread type
Create a variable called grouped that groups the sales DataFrame by the 'Bread' column using groupby.
Pandas
Need a hint?

Use sales.groupby('Bread') to group the data.

3
Iterate over the groups
Use a for loop with variables bread_type and group_data to iterate over grouped. Inside the loop, print the bread_type and the group_data DataFrame.
Pandas
Need a hint?

Use for bread_type, group_data in grouped: to loop through groups.

4
Display the grouped sales output
Run the program to print the bread type and the sales data for each group.
Pandas
Need a hint?

Check the console output to see each bread type and its sales rows.