numpy.nonzero()function is used to Compute the indices of the elements that are non-zero.
It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension.
The corresponding non-zero values in the array can be obtained with
arr[nonzero(arr)] . To group the indices by element, rather than dimension we can use
Syntax : numpy.nonzero(arr)
arr : [array_like] Input array.
Return : [tuple_of_arrays] Indices of elements that are non-zero.
Code #1 : Working
Input array :
[[ 0 8 0]
[ 7 0 0]
[-5 0 1]]
Indices of non zero elements : (array([0, 1, 2, 2], dtype=int64), array([1, 0, 0, 2], dtype=int64))
Code #2 :
Output array of non-zero number: [ 8 7 -5 1]
Code #3 :
indices of non-zero number: [[0 1] [1 0] [2 0] [2 2]]
- Reading Python File-Like Objects from C | Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Add Logging to a Python Script
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to Python Libraries
- zip() in Python
- SHA in Python
- SQL using Python | Set 1
- Use of min() and max() in Python
- Any & All in Python
- chr() in Python
- Python | a += b is not always a = a + b
- pow() in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.