Piecewise Category Codes With np.select
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `bucketize(x)`. Given a NumPy array `x`, return a new integer array mapping each element to a category code by range, using `np.select(condlist, choicelist)` with parallel condition and choice lists.
Requirements:
- `x < 0` → `-1`
- `0 <= x < 10` → `0`
- `10 <= x < 100` → `1`
- `x >= 100` → `2`
- Result shape matches the input.
For example:
```python
x = np.array([-5, 0, 3, 10, 99, 100, 250])
bucketize(x)
# array([-1, 0, 0, 1, 1, 2, 2])
```
```hint Condition order
`np.select` returns, for each element, the choice paired with the first condition that is true. Decide whether each condition needs both of its bounds or whether the position in the list can supply the lower one.
```
```hint Combining comparisons
If you write a condition with two bounds, check how Python groups `&` relative to `<` and `>=` before you run it.
```
### What a Strong Answer Covers
- How the condition list and the choice list pair up, and what `np.select` returns for each element
- Whether the conditions are mutually exclusive or depend on their order in the list
- Which code the boundary values 0, 10 and 100 receive
- The dtype and shape of the result
- What happens to an element that matches no condition, such as `nan`
### Follow-up Questions
- How does the `default` argument of `np.select` behave?
- When conditions overlap, which choice wins?
- How would you solve this without `np.select`?
Overview: Map each element of a NumPy array to an integer category code by value range using np.select with parallel condition and choice lists. It tests first-match semantics, boundary values, the default argument, and vectorized alternatives such as np.digitize.