Count Values per Bin With Explicit Edges in NumPy
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `hist_counts(a, edges)` that returns the per-bin counts of values in `a` using the explicit bin boundaries `edges`. This mirrors the first return value of `np.histogram(a, bins=edges)`, and you may delegate to `np.histogram` and return its first element.
Requirements:
- Return an integer array of length `len(edges) - 1` (counts only, not the edges).
- Each bin `[edges[i], edges[i+1])` is half-open, except the last bin `[edges[-2], edges[-1]]`, which includes both edges.
- Values outside `[edges[0], edges[-1]]` are excluded from all counts.
Example:
```python
a = np.array([0.0, 0.5, 1.0, 1.5, 2.0])
edges = np.array([0.0, 1.0, 2.0])
hist_counts(a, edges)
# array([2, 3])
# bin [0,1): {0.0, 0.5}; bin [1,2] (closed): {1.0, 1.5, 2.0}
```
```hint Two kinds of edge values
A value equal to an inner edge and a value equal to the last edge follow different rules. Check that your method treats `1.0` and `2.0` in the example differently.
```
### Constraints & Assumptions
- `edges` is 1-D and monotonically increasing.
- `a` is a 1-D numeric array and may contain values outside the edge range.
### What a Strong Answer Covers
- Returning only the counts when the edges are passed to `np.histogram` as an array.
- The half-open inner bins and the closed last bin, checked on values that sit exactly on an edge.
- Exclusion of values outside `[edges[0], edges[-1]]`.
- How the counts could be built by hand if `np.histogram` were not allowed.
### Follow-up Questions
- How would you compute counts across many rows of a 2-D array with shared edges?
- How does `np.digitize` relate to this task?
- How would you return weighted counts, where each value adds its own weight to its bin?
Overview: Implement per-bin counts for a NumPy array given explicit bin edges, matching np.histogram with half-open bins and a closed last bin. The question tests bin boundary rules, exclusion of values outside the edge range, and vectorized counting across one or many rows.