📖 Scenario: You work in a small store and have a list of sales records. Each record shows the product sold, the quantity sold, and the price per item. You want to find out the total quantity sold and the average price for each product.
🎯 Goal: Build a pandas DataFrame from the sales data, then use groupby with named aggregation to calculate the total quantity and average price per product.
📋 What You'll Learn
Create a pandas DataFrame called sales with columns product, quantity, and price using the exact data provided.
Create a variable called agg_funcs that holds the named aggregation dictionary for total quantity and average price.
Use sales.groupby('product').agg(**agg_funcs) to group and aggregate the data.
Print the resulting DataFrame.
💡 Why This Matters
🌍 Real World
Stores and businesses often need to summarize sales data to understand product performance and pricing trends.
💼 Career
Data analysts and data scientists use named aggregation in pandas to create clear, readable summaries of grouped data for reports and decision making.
Progress0 / 4 steps
1
Create the sales DataFrame
Create a pandas DataFrame called sales with these exact rows: {'product': ['apple', 'banana', 'apple', 'banana', 'orange'], 'quantity': [10, 5, 7, 3, 8], 'price': [0.5, 0.3, 0.55, 0.35, 0.8]}.
Pandas
Hint
Use pd.DataFrame and pass a dictionary with keys 'product', 'quantity', and 'price' and their respective lists.
2
Define the named aggregation dictionary
Create a variable called agg_funcs that holds a dictionary for named aggregation with these keys and values: total_quantity=('quantity', 'sum') and average_price=('price', 'mean').
Pandas
Hint
Define agg_funcs as a dictionary with keys for the new column names and values as tuples of (column, aggregation function).
3
Group and aggregate the sales data
Use sales.groupby('product').agg(**agg_funcs) to group the sales DataFrame by product and apply the named aggregation stored in agg_funcs. Store the result in a variable called summary.
Pandas
Hint
Use groupby('product') and then agg(**agg_funcs) to apply the named aggregation.
4
Print the summary DataFrame
Print the summary DataFrame to see the total quantity and average price for each product.
Pandas
Hint
Use print(summary) to display the grouped and aggregated data.
Practice
(1/5)
1. What is the main purpose of named aggregation in pandas?
easy
A. To assign custom names to aggregated summary columns
B. To rename columns before aggregation
C. To filter rows before grouping
D. To sort data after aggregation
Solution
Step 1: Understand aggregation in pandas
Aggregation combines data by groups to produce summary statistics.
Step 2: Role of named aggregation
Named aggregation lets you specify clear names for these summary columns, making results easier to read.
Final Answer:
To assign custom names to aggregated summary columns -> Option A
Quick Check:
Named aggregation = custom summary names [OK]
Hint: Named aggregation means naming summary columns clearly [OK]
Common Mistakes:
Confusing named aggregation with renaming columns before aggregation
Thinking it filters or sorts data
Assuming it changes the grouping keys
2. Which of the following is the correct syntax for using named aggregation in groupby.agg()?
easy
A. df.groupby('A').agg({'new_col': 'B', 'sum'})
B. df.groupby('A').agg('new_col' = ('B', 'sum'))
C. df.groupby('A').agg(new_col=('B', 'sum'))
D. df.groupby('A').agg(('B', 'sum') = 'new_col')
Solution
Step 1: Recall named aggregation syntax
Named aggregation uses keyword arguments with the format new_name=(column, function).
Step 2: Check each option
df.groupby('A').agg(new_col=('B', 'sum')) matches this syntax exactly: new_col=('B', 'sum'). Others have invalid syntax or misplaced equals signs.
Final Answer:
df.groupby('A').agg(new_col=('B', 'sum')) -> Option C
Quick Check:
Named aggregation syntax = new_name=(col, func) [OK]
Hint: Use new_name=(column, function) inside agg() [OK]
Common Mistakes:
Using equals sign inside dictionary instead of keyword argument
You want to create a summary DataFrame grouped by 'Store' with:
Total sales named 'total_sales'
Average returns named 'avg_returns'
Count of sales entries named 'sales_count'
Which code correctly uses named aggregation to achieve this?
hard
A. df.groupby('Store').agg(sum('Sales') as total_sales, mean('Returns') as avg_returns, count('Sales') as sales_count)
B. df.groupby('Store').agg(total_sales=('Sales', 'sum'), avg_returns=('Returns', 'mean'), sales_count=('Sales', 'count'))
C. df.groupby('Store').agg(total_sales='sum', avg_returns='mean', sales_count='count')
D. df.groupby('Store').agg({'total_sales': ('Sales', 'sum'), 'avg_returns': ('Returns', 'mean'), 'sales_count': ('Sales', 'count')})
Solution
Step 1: Recall named aggregation syntax
Use keyword arguments with new_name=(column, function) inside agg().
Step 2: Evaluate each option
df.groupby('Store').agg(total_sales=('Sales', 'sum'), avg_returns=('Returns', 'mean'), sales_count=('Sales', 'count')) correctly uses named aggregation syntax. df.groupby('Store').agg({'total_sales': ('Sales', 'sum'), 'avg_returns': ('Returns', 'mean'), 'sales_count': ('Sales', 'count')}) uses a dictionary but this is not valid for named aggregation. df.groupby('Store').agg(total_sales='sum', avg_returns='mean', sales_count='count') uses strings without specifying columns. df.groupby('Store').agg(sum('Sales') as total_sales, mean('Returns') as avg_returns, count('Sales') as sales_count) uses invalid syntax.
Final Answer:
df.groupby('Store').agg(total_sales=('Sales', 'sum'), avg_returns=('Returns', 'mean'), sales_count=('Sales', 'count')) -> Option B
Quick Check:
Named aggregation = keyword args with (col, func) tuples [OK]
Hint: Use new_name=(col, func) for multiple summaries [OK]
Common Mistakes:
Using dictionary instead of keyword arguments
Passing only function names without columns
Trying SQL-like syntax inside agg()
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.