📖 Scenario: You work in a company that collects sales data from different stores. Each store has sales numbers for several products. You want to compare sales within each store by normalizing the sales numbers.
🎯 Goal: You will create a pandas DataFrame with sales data, then use groupby and transform to normalize sales within each store. Finally, you will print the normalized sales.
📋 What You'll Learn
Create a pandas DataFrame named sales_data with columns 'Store' and 'Sales' using exact values
Create a variable mean_sales that stores the mean sales per store using groupby and transform
Create a new column 'Normalized_Sales' in sales_data by subtracting mean_sales from 'Sales'
Print the sales_data DataFrame to show the normalized sales
💡 Why This Matters
🌍 Real World
Normalizing sales data within groups helps compare performance fairly across stores by removing store-level differences.
💼 Career
Data analysts and data scientists often use groupby and transform in pandas to prepare and normalize data for analysis and reporting.
Progress0 / 4 steps
1
Create the sales data DataFrame
Create a pandas DataFrame called sales_data with two columns: 'Store' and 'Sales'. Use these exact values: 'Store': ['A', 'A', 'B', 'B', 'B', 'C'], 'Sales': [100, 150, 200, 210, 190, 300].
Pandas
Hint
Use pd.DataFrame with a dictionary containing the two columns and their values.
2
Calculate mean sales per store using groupby and transform
Create a variable called mean_sales that stores the mean sales for each store. Use sales_data.groupby('Store')['Sales'].transform('mean') to calculate it.
Pandas
Hint
Use groupby('Store')['Sales'].transform('mean') to get the mean sales for each row's store.
3
Create normalized sales column
Create a new column in sales_data called 'Normalized_Sales' by subtracting mean_sales from the 'Sales' column.
Pandas
Hint
Subtract the mean_sales Series from the 'Sales' column and assign it to a new column.
4
Print the normalized sales DataFrame
Print the sales_data DataFrame to display the original sales and the normalized sales values.
Pandas
Hint
Use print(sales_data) to show the DataFrame with normalized sales.
Practice
(1/5)
1. What does the transform() function do when used after groupby() in pandas?
easy
A. It applies a function to each group and returns a result aligned with the original data.
B. It removes duplicate rows from each group.
C. It aggregates groups into a single summary value.
D. It sorts the groups in ascending order.
Solution
Step 1: Understand groupby and transform roles
groupby() splits data into groups, and transform() applies a function to each group but keeps the original data shape.
Step 2: Identify transform output alignment
The output of transform() matches the original data's index, allowing normalized or transformed values to be added back easily.
Final Answer:
It applies a function to each group and returns a result aligned with the original data. -> Option A
Quick Check:
transform() returns aligned group results [OK]
Hint: transform() keeps original data shape after group operation [OK]
Common Mistakes:
Thinking transform aggregates to one value per group
Confusing transform with apply or aggregate
Assuming transform changes data order
2. Which of the following is the correct syntax to normalize a column 'score' within groups defined by 'team' using transform() in pandas?
easy
A. df['score_norm'] = df.transform('team')['score'].groupby(lambda x: (x - x.mean()) / x.std())
B. df['score_norm'] = df.groupby('team')['score'].apply(lambda x: (x - x.mean()) / x.std())
For team 'A': scores are 10 and 20. Normalized: (10-10)/(20-10)=0.0, (20-10)/(20-10)=1.0. For team 'B': scores 30 and 40 normalized similarly to 0.0 and 1.0.
Step 2: List normalized values in original order
Values are [0.0, 1.0, 0.0, 1.0] matching the original row order.
Final Answer:
[0.0, 1.0, 0.0, 1.0] -> Option A
Quick Check:
Min-max normalization per group = [0.0,1.0,0.0,1.0] [OK]
Hint: Min-max normalize each group separately with transform [OK]
Common Mistakes:
Normalizing across entire DataFrame, not per group
You want to add a column 'sales_norm' that normalizes sales within each region using z-score normalization. However, some regions have zero standard deviation. How can you safely compute 'sales_norm' without errors and keep zero for those groups?
hard
A. Use apply instead of transform to avoid errors.
B. Use transform with a lambda that checks std and returns zero if std is zero.
C. Drop groups with zero std before normalization.
D. Replace sales with mean before normalization.
Solution
Step 1: Identify problem with zero std groups
Groups with identical sales have std=0, causing division by zero in z-score.
Step 2: Use conditional lambda in transform
Write a lambda that checks if std is zero; if yes, return zeros, else perform normalization.
Final Answer:
Use transform with a lambda that checks std and returns zero if std is zero. -> Option B
Quick Check:
Conditional transform avoids zero division [OK]
Hint: Check std inside lambda; return zeros if std=0 [OK]
Common Mistakes:
Using apply which changes output shape
Dropping data instead of handling zero std
Ignoring zero std causing errors
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.