Extracting non-zero Values in an Array
The first step is to learn how to fetch the non-zero elements in a NumPy array. For that, we can use the nonzero() function. The function takes an input array and returns the indices of the non-zero elements. An example is as shown:
import numpy as np
arr = np.array([[1,2,3,4], [5,6,7,8]])
print(np.nonzero(arr))
The code above returns a tuple of arrays containing the indices of the non-zero elements in each dimension.
An example output is shown below:
We can use the input from this function to determine the min and max values using their respective functions.
NumPy min non-zero Value
Let us take a simple one-dimensional array holding the elements as shown below:
We can use the indices returned from the above function to get the actual values. For example:
The above operation uses array indexing to get the non-zero array elements.
We can wrap the above operation inside the np.min() function to get the min value. An example is as shown:
The above code should return the minimum value in the array.
NOTE: This operation will work on N-dimensional arrays.
NumPy max non-zero Value
We can simply replace the np.min() function with np to fetch the maximum value with np.max().
An example is as illustrated in the code below:
Closing
In this tutorial, we learned how we could use the NumPy nonzero and min functions to determine the minimum value in an array, excluding zero values.
Thanks for reading!!