BasicsPandasGroupByMetaAmazonUber
Problem
Implement sales_by_category(df) returning a DataFrame with columns ['category', 'sales'] containing total summed sales per category, sorted by category ascending with a reset index.
Why It Matters: Grouping and summing metrics by dimension is the core Pandas equivalent of SQL GROUP BY ... SUM(...).
Function Signature
import pandas as pd
def sales_by_category(df: pd.DataFrame) -> pd.DataFrame:
Sample Input & Output
Example 1: Multiple Categories
Input:
| category | sales |
|---|---|
| Books | 20.0 |
| Tech | 150.0 |
| Books | 30.0 |
Expected Output:
| category | sales |
|---|---|
| Books | 50.0 |
| Tech | 150.0 |
Explanation: Books sums to 20.0 + 30.0 = 50.0; Tech sums to 150.0, sorted alphabetically.
Example 2: Single Category
Input:
| category | sales |
|---|---|
| Food | 12.5 |
| Food | 7.5 |
Expected Output:
| category | sales |
|---|---|
| Food | 20.0 |
Explanation: Collapses all rows into one summary row ('Food', 20.0).
Constraints & Edge Cases
- Return columns
['category', 'sales']sorted bycategoryascending. - Use
as_index=Falseso'category'stays a regular column. - Sort by
'category'ascending and reset the index.
Constraints & Evaluation Criteria
- Return columns `['category', 'sales']` sorted by `category` ascending.
Hints
Python 3⌘/Ctrl+Enter to Run · ⌘/Ctrl+Shift+Enter to Submit
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
Books + Tech rows
Expected Output / Criteria
Books=35, Tech=120