Count the elements of a NumPy array that are strictly greater than a threshold
Quick Overview
Write a NumPy function that counts how many elements of an array are strictly greater than a threshold and returns a plain Python integer, with no Python loop. It tests vectorized comparisons, how NumPy reduces boolean arrays, the strict boundary case and NumPy return types.
Count the elements of a NumPy array that are strictly greater than a threshold
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `count_above(arr, threshold)` returning how many elements of a NumPy array are strictly greater than `threshold`.
Requirements:
- Sum the mask `arr > threshold` with `.sum()` (no Python loop).
- Return a built-in Python `int` via `int(...)`, not a NumPy integer.
For example:
```python
arr = np.array([1, 5, 3, 8, 2])
count_above(arr, 3) # 2 (the elements 5 and 8)
```
```hint Watch the boundary
An element equal to `threshold` must not be counted. Test with a threshold that appears in the array, as 3 does in the example.
```
### What a Strong Answer Covers
- How the comparison is done for the whole array in one vectorized step, and what that step produces.
- Why reducing that result gives the count.
- The strict boundary, so values equal to the threshold are excluded.
- The type of the returned value and why it is converted.
- Time cost, the memory used by the intermediate array, and inputs with NaN values or no elements.
### Follow-up Questions
- How would you count along a single axis of a 2-D array?
- How does `.sum()` compare with `np.count_nonzero` for this count?
- How would you count the elements that fall in a range, strictly above `low` and at most `high`?
- What would you change if the array is too large to hold a full boolean mask in memory?
Overview: Write a NumPy function that counts how many elements of an array are strictly greater than a threshold and returns a plain Python integer, with no Python loop. It tests vectorized comparisons, how NumPy reduces boolean arrays, the strict boundary case and NumPy return types.