Find Maximum Value in NumPy Array along an Axis


NumPy - Maximum value in array along an axis

You can find the maximum or largest value of a Numpy array, not only in the whole numpy array, but also along a specific axis or set of axes.

To get the maximum value of a NumPy Array along an axis, use numpy.amax() function.

Syntax

The syntax of numpy.amax() function is given below.

max_value = numpy.amax(arr, axis)

If you do not provide any axis, the maximum of the array is returned.

You can provide axis or axes along which to operate. If axis is a tuple of integers representing the axes, then the maximum is selected over these specified multiple axes.

Examples

1. Maximum value along an axis

In the following example, we will take a numpy array with random numbers and then find the maximum of the array along an axis using amax() function.

We shall find the maximum value along axis=0 and axis=1 separately.

Python Program

import numpy as np

# 2D array => 2 axes
arr = np.random.randint(10, size=(4,5))
print('array\n', arr)

#find maximum value along axis=0
amax_value = np.amax(arr, axis=0)
print('Maximum value of the array along axis=0')
print(amax_value)

#find maximum value along axis=1
amax_value = np.amax(arr, axis=1)
print('Maximum value of the array along axis=1')
print(amax_value)

Output

array
 [[4 3 0 0 9]
 [7 5 7 0 5]
 [2 8 1 8 7]
 [3 8 5 0 2]]
Maximum value of the array along axis=0
[7 8 7 8 9]
Maximum value of the array along axis=1
[9 7 8 8]

2. Maximum value along multiple axes

As already mentioned, we can calculate the maximum value along multiple axes. Provide all the axis, as a tuple, along which you would like to find the maximum value.

Python Program

import numpy as np

# 2D array => 2 axes
arr = np.random.randint(9, size=(2,2,4))
print(arr)

# find maximum value along axis=0,2
amax_value = np.amax(arr, axis=(0, 2))
print('Maximum value of the array along axis=(0,2)')
print(amax_value)

Output

array
 [[[4 3 6 5]
  [4 8 8 3]]

 [[5 3 1 2]
  [8 0 2 5]]]
Maximum value of the array along axis=(0,2)
[6 8]

Summary

In this Numpy Tutorial, we learned how to find the maximum value in a numpy array along an axis or multiple axes combined.