Python

# NumPy non-zero min

This short tutorial will discuss how you can determine the minimum value in a NumPy array, excluding zero values. Before we get started, you must be familiar with the NumPy non-zero () function.

## 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
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:

(array([0, 0, 0, 0, 1, 1, 1, 1], dtype=int64), array([0, 1, 2, 3, 0, 1, 2, 3], dtype=int64))

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:

arr = np.array([0,1,2,3,0,0,4,5])

We can use the indices returned from the above function to get the actual values. For example:

print(arr[np.nonzero(arr)])

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:

print(np.min(arr[np.nonzero(arr)]))

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:

print(np.max(arr[np.nonzero(arr)]))

## 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.