Summarize sales by region with pandas named aggregation
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `sales_summary(df)` for a DataFrame with columns `region`, `sales` and `qty`. Return one summary row per `region` using named aggregation.
Requirements:
- Index is `region`, sorted ascending.
- Exactly three columns in order: `total_sales` (sum of `sales`), `avg_sales` (mean of `sales`), `n_orders` (row count).
- Use named aggregation via `df.groupby('region').agg(...)`.
- Do not use the dict-of-lists `agg` syntax, which returns two-level column labels that then need renaming.
Example:
```python
df = pd.DataFrame({
'region': ['east', 'west', 'east'],
'sales': [100, 200, 50],
'qty': [1, 2, 1],
})
sales_summary(df)
# total_sales avg_sales n_orders
# region
# east 150 75.0 2
# west 200 200.0 1
```
```hint Keyword arguments
Each keyword you pass to `.agg()` becomes an output column, and its value is a `(source_column, function)` pair. For the row count, check whether the function you pick skips rows where `sales` is missing.
```
### What a Strong Answer Covers
- A single `groupby(...).agg(...)` call whose keyword arguments produce flat columns with the required names and order.
- Why the result is indexed by `region` and sorted ascending, and whether any extra call is needed for that.
- The choice of counting function for `n_orders` and how it treats missing `sales` values.
- The dtypes of the three output columns and edge cases such as missing region keys.
### Follow-up Questions
- How does `size` differ from `count` here?
- How would you keep `region` as a column instead of the index?
- How would you add total `qty` and a custom aggregation, such as the share of orders with `qty` above 1, in the same call?
Overview: Write a pandas function that groups a sales DataFrame by region and returns total sales, average sales and order count as flat columns in a fixed order using named aggregation. It tests groupby mechanics, control over output column names and order, and how counting functions treat missing values.