Finding Min and Max of a Numpy Matrix

12.07.2020

Intro

In this quick tip we will learn how to find min and max values of a NumPy array. NumPy provides some easy access to these values so you don't need to loop over the matrix.

Example

import numpy as np

# create a matrix
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# Get the Max
print(np.max(matrix))
print(np.min(matrix))

# Get the max/min of each column
print(np.max(matrix, axis=0))
print(np.min(matrix, axis=0))

# Get the max/min of each row
print(np.max(matrix, axis=1))
print(np.min(matrix, axis=1))

In the example above, we use the np.max and np.min function to return the max and min of the whole matrix. We can also use the axis argument to specify that we want the max or min of each column or row. NumPy will return an array of each max or min when using axis.