How to find the minimum value in each row of a numpy array ?


Introduction

Finding the minimum value and its corresponding index is important for example to find nearest points in a distance matrix.

In this article, we will discuss how to find the minimum value in each row of a numpy array.

Creating a numpy array

To create a numpy array, we start by importing the numpy library as np.

First, let's create a numpy array consisting of random integers between 0 and 100. The array should have a shape of 6 rows and 5 columns (By setting a random seed of 42, we ensure reproducibility of the random values generated.):

import numpy as np

np.random.seed(42)

data = np.random.randint(0,100,(6,5))

print( data )

For instance, the provided code will generate:

array([[51, 92, 14, 71, 60],
       [20, 82, 86, 74, 74],
       [87, 99, 23,  2, 21],
       [52,  1, 87, 29, 37],
       [ 1, 63, 59, 20, 32],
       [75, 57, 21, 88, 48]])

Finding the minimum value in each row

To determine the minimum value in each row of a numpy array, we can utilize the min() function by specifying the argument axis = 1. This method allows us to efficiently extract the lowest value across each row:

data.min(axis=1)

In our example, this function will provide the following output:

array([14, 20,  2,  1,  1, 21])

Finding the index of the minimum value in each row

Furthermore, if we want to find the index of the minimum value in each row, we can use the argmin() function. This function returns the index of the minimum value along a given axis:

data.argmin(axis=1)

In our example, this function will provide the following output:

array([2, 0, 3, 1, 0, 2])

It is worth noting that there might be cases where certain rows have multiple minimum values. In such cases, both min() and argmin() functions return only the first occurrence of that value

Visualize numpy arrays by plotting heatmaps with annotations

Seaborn offers a convenient way to visualize numpy arrays by plotting heatmaps with annotations. This feature is particularly useful for illustrating the aforementioned example, enhancing clarity and comprehension.

import seaborn as sns
import matplotlib.pyplot as plt

sp = sns.heatmap(data, annot=True)

sp.set_title("How to find the minimum value \n in each row of a numpy array ?")

plt.savefig('min_value_in_each_row_of_a_numpy_array_01.png', bbox_inches='tight', facecolor='white')

How to find the minimum value in each row of a numpy array ?
How to find the minimum value in each row of a numpy array ?

References

Links Site
numpy.min numpy.org
numpy.argmin numpy.org
seaborn.heatmap seaborn.pydata.org
Image

of