Count the non-zero entries in each column of a 2-D NumPy array
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 2-D NumPy array `arr`, return a 1-D array where element `i` is the number of non-zero entries in column `i`.
Requirements:
- Reduce over the row axis.
- Return a 1-D array of length `arr.shape[1]`.
- No Python-level `for`/`while` loop over rows or columns.
For example:
```python
arr = np.array([[0, 1, 0],
[2, 0, 0],
[3, 4, 0]])
nonzero_per_column(arr) # array([2, 2, 0])
```
```hint Pick the axis to collapse
In a NumPy reduction, the `axis` you pass is the dimension that disappears from the result. Work out which axis number has to vanish to leave one value per column.
```
### What a Strong Answer Covers
- Which axis is reduced, and why that leaves one value per column.
- A vectorized NumPy call that does the count with no Python loop.
- The shape of the result, checked against the example.
- Edge cases such as an all-zero column, an array with no rows, NaN values and input that is not 2-D.
- Time and memory cost.
### Follow-up Questions
- How would you count non-zero entries per row instead?
- How would you return the fraction of non-zero entries in each column, and what happens when the array has no rows?
- Should NaN entries count as non-zero, and how would you exclude them?
Overview: Given a 2-D NumPy array, return a 1-D array holding the number of non-zero entries in each column, without Python loops. It tests reductions along an axis, the shape of the result, and edge cases such as all-zero columns, empty arrays and NaN values.