numpy.nonzero() in Python

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 transpose(nonzero(arr)).

Syntax : numpy.nonzero(arr)



Parameters :
arr : [array_like] Input array.

Return : [tuple_of_arrays] Indices of elements that are non-zero.

Code #1 : Working

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program explaining
# nonzero() function
  
import numpy as geek
arr = geek.array([[0, 8, 0], [7, 0, 0], [-5, 0, 1]])
  
print ("Input  array : \n", arr)
    
out_tpl = geek.nonzero(arr)
print ("Indices of non zero elements : ", out_tpl) 

chevron_right


Output :

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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program for getting
# The corresponding non-zero values:
out_arr = arr[geek.nonzero(arr)]
  
print ("Output array of non-zero number: ", out_arr) 

chevron_right


Output :

Output array of non-zero number:  [ 8  7 -5  1]

 
Code #3 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program for grouping the indices
# by element, rather than dimension
  
out_ind = geek.transpose(geek.nonzero(arr))
  
print ("indices of non-zero number: \n", out_ind) 

chevron_right


Output :

indices of non-zero number: 
 [[0 1]
 [1 0]
 [2 0]
 [2 2]]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.