Compute Grouped Means in NumPy With np.bincount
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Given a 1-D values array `D` and an integer label array `S` of the same length (`S[i]` is the group id of `D[i]`), return a 1-D array whose position `g` holds the mean of values labelled `g`.
Requirements:
- Sums via `np.bincount(S, weights=D)`, counts via `np.bincount(S)`, return `sums / counts`.
- Output length is `S.max() + 1` (ids need not be contiguous).
- Cast `D` to float before dividing.
- Empty groups give `0/0`: leave them as `nan` or fill a default.
- No Python loops over rows.
For example:
```python
D = np.array([1.0, 3.0, 5.0, 7.0, 9.0])
S = np.array([0, 1, 0, 1, 2])
# Output: array([3., 5., 9.])
```
```hint Empty bins
`np.bincount` returns one bin for every id from 0 up to the largest label, including ids that never appear. Check what the division does in those bins and whether NumPy warns about it.
```
### Constraints & Assumptions
- `len(D) == len(S)`.
- Labels in `S` are non-negative integers.
### What a Strong Answer Covers
- Two `np.bincount` calls (weighted for sums, unweighted for counts) and an elementwise division, with no Python loop over rows.
- Why both arrays have length `S.max() + 1` and line up group for group.
- How ids that never appear are handled, including any warnings from the division.
- The dtype of the result, and what happens with negative, non-integer or very large labels.
- Time and space cost, keeping the number of rows separate from the output length.
### Follow-up Questions
- How would you handle group ids that are sparse or non-integer keys?
- How would you extend this to grouped variance in one pass?
- When would you reach for `np.add.at` instead of `np.bincount`?
Overview: Compute the mean of a NumPy values array within each integer group label using np.bincount, with no Python loop over rows. It tests vectorized group-by thinking, handling of empty groups and dtypes, and extensions to sparse keys and grouped variance.