BasicsPandasAggregationMetaAmazonUber
Problem
Implement dept_summary(df) computing avg_salary (mean of salary) and headcount (count of non-null salary) per dept, returning columns ['dept', 'avg_salary', 'headcount'] sorted by dept ascending.
Why It Matters: Named aggregations (.agg(col_name=('src', 'func'))) produce clean, flat summary tables without messy MultiIndex headers.
Function Signature
import pandas as pd
def dept_summary(df: pd.DataFrame) -> pd.DataFrame:
Sample Input & Output
Example 1: Two Departments
Input:
| dept | salary |
|---|---|
| Eng | 120.0 |
| Sales | 80.0 |
| Eng | 140.0 |
Expected Output:
| dept | avg_salary | headcount |
|---|---|---|
| Eng | 130.0 | 2 |
| Sales | 80.0 | 1 |
Explanation: Eng has mean 130.0 and headcount 2; Sales has mean 80.0 and headcount 1.
Example 2: Single-Person Department
Input:
| dept | salary |
|---|---|
| HR | 95.0 |
Expected Output:
| dept | avg_salary | headcount |
|---|---|---|
| HR | 95.0 | 1 |
Explanation: Returns avg_salary = 95.0 and headcount = 1.
Constraints & Edge Cases
- Return columns
['dept', 'avg_salary', 'headcount']sorted bydeptascending. - Use
.groupby('dept', as_index=False).agg(avg_salary=('salary', 'mean'), headcount=('salary', 'count')). - Sort by
deptascending and reset index.
Constraints & Evaluation Criteria
- Return columns `['dept', 'avg_salary', 'headcount']` sorted by `dept` ascending.
Hints
Python 3⌘/Ctrl+Enter to Run · ⌘/Ctrl+Shift+Enter to Submit
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
Eng (2) & Sales (1)
Expected Output / Criteria
Eng avg=150, count=2