Assign Values to Bins With np.digitize in NumPy
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `bin_indices(x, edges)` that assigns each value in `x` to a bin defined by monotonically increasing `edges`. Return an integer `np.ndarray` of the same shape as `x` with each value's bin index.
Requirements:
- Compute with `np.digitize(x, edges)`.
- Index `i` satisfies `edges[i-1] <= v < edges[i]`.
- Values below the first edge get `0`, and values at or above the last edge get `len(edges)`.
Example:
```python
x = np.array([0.2, 6.4, 3.0, 1.6])
edges = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
bin_indices(x, edges) # array([1, 4, 3, 2])
```
```hint Check the boundaries
Before writing code, work out by hand which index a value exactly equal to an edge should get, for example `1.0` and `10.0` with the edges above.
```
### Constraints & Assumptions
- `edges` is a 1-D array sorted in increasing order.
- `x` can have any shape, and the output must have the same shape.
### What a Strong Answer Covers
- The call to `np.digitize` and the meaning of its default `right=False`.
- How values below the first edge, exactly on an edge, and at or above the last edge are indexed.
- How the indices relate to the `len(edges) - 1` in-range bins.
- Time and space complexity of the lookup.
### Follow-up Questions
- How does the `right` argument change the bin boundaries?
- How would you clamp out-of-range values into the first and last bins?
- How would you get the same indices with `np.searchsorted`?
Overview: Write a NumPy function that maps each value to a bin index given increasing bin edges, with fixed rules for values below, on, and above the edges. The question tests np.digitize boundary semantics, handling of out-of-range values, and vectorized binary search over sorted edges.