How "nonzero()" works?



0

Answer:

# "nonzero()" returns the location of nonzero elements in the list/tuple...

import numpy as np

# 1D case
arr = np.array([8, 11, 2, 9, 6, 0, 0, 0, 0, 6])
nz_index = np.nonzero(arr)
print("1D Nonzeo indices", nz_index) 
# Here, 5th, 6th, 7th, 8th indices have value 0, so these indices will not be considered by nonzero() return

# 2D case
arr_2d = np.array([[0, 11, 2],[3, 4, 0]])
nz_index_2d = np.nonzero(arr_2d)
print("2D nonzero indices", nz_index_2d)

# In matrix, we use (row, col) to define any single element e.g. (1,2)

# A simple 2 rows x 3 columns (3x2) matrix can be represented as (zero index system starts with 0),
# [ [ (0,0) (0,1) (0,2) ]
#   [ (1,0) (1,1) (1,2) ] ]

# In the below 2x3 matrix,
#  [ [0, 11, 2]
#    [3, 4,  0] ]

# nonzero elements are in the locations (0,1), (0,2), (1,0) and (1,1) --> (row,col) order
# so it will take row indices --> [0,0,1,1] and column indices --> [1,2,0,1] separately and returns two arrays, one for row indices and one for column indices
# So we get --> (array([0, 0, 1, 1], dtype=int64), array([1, 2, 0, 1], dtype=int64))