numpy.nonzero () in Python

It returns a tuple of arrays, one for each dimension arr, containing the indices of the nonzero elements in that dimension. 
The corresponding nonzero values ​​in the array can be obtained using arr [nonzero (arr)] . To group indices by element rather than size, 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: Work

# Python program explaining
# non-null () function

  

import numpy as geek

arr = geek.array ([[ 0 , 8 , 0 ], [ 7 , 0 , 0 ], [ - 5 , 0 , 1 ]])

 

print ( "Input array:" , arr)

  

out_tpl = geek .nonzero (arr)

print ( "Indices of non zero elements:" , out_tpl) 

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:

# Python getter
# Corresponding nonzero values:

out_arr = arr [geek.nonzero (arr)]

 

print ( "Output array of non- zero number: " , out_arr) 

Output:

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

Code # 3:

# Python program for grouping indexes
# by element, not by size

 

out_ind = geek.transpose (geek.nonzero (arr))

  

print ( " indices of non-zero number: " , out_ind) 

Output:

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