Non-Zero Indices of a 1-D NumPy Array With np.nonzero
Quick Overview
Return the positions of the non-zero entries of a 1-D NumPy array using np.nonzero. It tests whether you know the shape of what np.nonzero gives back, how to unpack it for a single axis, and how all-zero, empty or NaN inputs behave.
Non-Zero Indices of a 1-D NumPy Array With np.nonzero
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 1-D NumPy array, return the indices of its non-zero elements as a 1-D integer array. Use `np.nonzero` and return the first (only) element of its returned tuple.
Requirements:
- Return a 1-D integer array of indices.
- Return an empty array when no elements are non-zero.
Example:
```python
a = np.array([0, 3, 0, 5, 7, 0])
# Output: array([1, 3, 4])
```
```hint Look at what comes back
Print `np.nonzero(a)` for a small 1-D array and check its type and length before deciding what to return.
```
### Constraints & Assumptions
- The input is a 1-D NumPy array (numeric or boolean).
- The array may contain no non-zero elements at all.
### What a Strong Answer Covers
- Why `np.nonzero` returns a tuple with one index array per axis, and how to unpack it for a 1-D input.
- The dtype and the order of the returned indices.
- The all-zero case, and which values count as non-zero (NaN, `-0.0`, booleans).
- A loop-free implementation and its cost.
### Follow-up Questions
- How does the result change for a 2-D array, and how would you get (row, column) pairs?
- How do `np.flatnonzero(a)`, `np.where(a)` and `np.argwhere(a)` compare with `np.nonzero(a)[0]`?
- Does a NaN in the array show up in the result?
- How would you count the non-zero elements without building the index array?
Overview: Return the positions of the non-zero entries of a 1-D NumPy array using np.nonzero. It tests whether you know the shape of what np.nonzero gives back, how to unpack it for a single axis, and how all-zero, empty or NaN inputs behave.
Given a 1-D NumPy array, return the indices of its non-zero elements as a 1-D integer array. Use np.nonzero and return the first (only) element of its returned tuple.
Requirements:
Return a 1-D integer array of indices.
Return an empty array when no elements are non-zero.