Contents
Maximum Value of a Python Numpy 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 – numpy.amax()
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.
Example 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(arr)
#find maximum value along axis=0
amax_value = np.amax(arr, axis=0)
print('Maximum value of the array along axis=0 is:')
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 is:')
print(amax_value)
Run Output
[[4 8 8 9 4]
[8 5 2 4 0]
[2 3 3 8 7]
[6 6 5 0 4]]
Maximum value of the array along axis=0 is:
[8 8 8 9 7]
Maximum value of the array along axis=1 is:
[9 8 8 6]
Example 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) is:')
print(amax_value)
Run Output
[[[5 6 1 2]
[5 5 3 6]]
[[5 2 3 3]
[7 5 7 4]]]
Maximum value of the array along axis=(0,2) is:
[6 7]
Summary
In this Numpy Tutorial of Python Examples, we learned how to find the maximum value of a numpy array along an axis or multiple axes combined.