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]])

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:


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:



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!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list