Skip to content

Commit 038cc2f

Browse files
[Term Entry] Python NumPy - ndarray: nonzero()
* docs: add nonzero() term under NumPy ndarray concept * Update nonzero.md with example descriptions, meta data, and backlinks * Minor changes ---------
1 parent 6386622 commit 038cc2f

File tree

1 file changed

+64
-0
lines changed
  • content/numpy/concepts/ndarray/terms/nonzero

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
Title: '.nonzero()'
3+
Description: 'Returns the indices of the array elements that are non-zero.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Array'
9+
- 'Data'
10+
- 'NumPy'
11+
CatalogContent:
12+
- 'learn-python-3'
13+
- 'paths/data-science'
14+
---
15+
16+
The **`.nonzero()`** method returns the indices of elements in a NumPy array that are non-zero or evaluate to `True`. It is often used to locate positions of meaningful or valid data within an array.
17+
18+
## Syntax
19+
20+
```pseudo
21+
ndarray.nonzero()
22+
```
23+
24+
**Parameters:**
25+
26+
This method takes no parameters.
27+
28+
**Return value:**
29+
30+
Returns a [tuple](https://www.codecademy.com/resources/docs/python/tuples) of arrays, one for each dimension, containing the indices of elements that are non-zero.
31+
32+
## Example: Finding Non-Zero Elements in a 1D Array
33+
34+
In this example, the indices of all non-zero elements in a 1D NumPy array are returned:
35+
36+
```py
37+
import numpy as np
38+
39+
arr = np.array([0, 2, 0, 4, 5])
40+
result = arr.nonzero()
41+
print(result)
42+
```
43+
44+
The output of this code is:
45+
46+
```shell
47+
(array([1, 3, 4]),)
48+
```
49+
50+
## Codebyte Example
51+
52+
In this example, the positions of non-zero elements in a 2D array are identified:
53+
54+
```codebyte/python
55+
import numpy as np
56+
57+
a = np.array([[0, 5, 0],
58+
[7, 0, 9]])
59+
60+
rows, cols = a.nonzero()
61+
62+
for r, c in zip(rows, cols):
63+
print(f"Non-zero element {a[r, c]} found at position ({r}, {c})")
64+
```

0 commit comments

Comments
 (0)