Distinct Products and Total Sales per Region in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `distinct_and_total(df)`. Given a DataFrame with columns `region`, `product` and `sales`, return a per-region summary DataFrame.
The result must meet these requirements:
- Index by `region`, sorted ascending.
- `n_products`: number of distinct `product` values per region (NaN excluded).
- `total_sales`: sum of `sales` per region.
- Use named aggregation via `.agg()`.
For example:
```python
df = pd.DataFrame({
'region': ['E', 'E', 'W', 'W', 'W'],
'product': ['a', 'a', 'b', 'c', 'c'],
'sales': [10, 5, 3, 7, 2],
})
distinct_and_total(df)
# n_products total_sales
# region
# E 1 15
# W 2 12
```
```hint Count the right thing
Region E has two rows but only one distinct product. Check which aggregation function returns 1 for that group, and what it does with a missing product.
```
### Constraints & Assumptions
- `df` has the columns `region`, `product` and `sales`, and `sales` is numeric.
- `product` may contain NaN, and a missing product does not count as a distinct product.
- The output has exactly two columns, `n_products` and `total_sales`, with `region` as the index.
### What a Strong Answer Covers
- One `groupby` on `region` followed by a single `.agg()` call that uses named aggregation for both output columns.
- A distinct count for `n_products` that skips NaN, and why a plain row count gives the wrong number.
- How the `region` index ends up sorted ascending.
- What missing values in `product`, `sales` and `region` do to the result.
### Follow-up Questions
- How would you keep `region` as a column instead of the index?
- How would you also count NaN products as distinct?
- Rows with a missing `region` disappear from the result. How would you keep them as their own group?
Overview: Write a pandas function that groups sales rows by region and returns the number of distinct products and the total sales for each region. It tests groupby with named aggregation, distinct counts that skip missing values, and control over the order of the resulting index.