Per-Row Gather With np.take_along_axis
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Given a 2-D array `a` of shape `(m, n)` and a 1-D integer array `cols` of length `m` (one column index per row), implement `select_per_row(a, cols)` returning the 1-D array of length `m` whose i-th entry is `a[i, cols[i]]`.
Requirements:
- Use `np.take_along_axis` with `axis=1`, reshaping `cols` to `(m, 1)` (or equivalent advanced indexing).
- No explicit Python-level loop over rows.
For example:
```python
a = np.array([[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])
cols = np.array([2, 0, 1])
select_per_row(a, cols) # -> array([12, 20, 31])
```
```hint Index shape
`np.take_along_axis` expects an index array with as many dimensions as `a`. Compare the shape of `cols` with that, and the shape of what comes back with the 1-D result you must return.
```
### What a Strong Answer Covers
- Why the index array needs shape `(m, 1)` and how each index pairs with its row
- Turning the `(m, 1)` result into a 1-D array of length `m`
- The equivalent advanced-indexing form and why it gives the same result
- What happens when `cols` has the wrong dtype, the wrong length or out-of-range values
### Follow-up Questions
- How would you generalize this to gather along an arbitrary axis of an N-D array?
- How would you set those selected elements instead of reading them?
- What changes if each row needs `k` columns, so `cols` has shape `(m, k)`?
Overview: Given a 2D NumPy array and one column index per row, return the chosen element from each row as a 1D array without a Python loop. It tests np.take_along_axis, how index array shapes broadcast against the source, and the equivalent advanced indexing form.