To find the Maximum and Minimum value in a NumPy Array
In this tutorial, we’ll learn about NumPy library, NumPy array and how to calculate the maximum and minimum value in NumPy array.
np.amax(array)
np.amin(array)
These two functions can be used to achieve our target here.
The maximum and minimum value in NumPy Array
import numpy as np # 1D array arr = np.arange(10) print("arr : ", arr) print("Maximum of arr : ", np.amax(arr)) print("Minimum of arr : ", np.amin(arr)) # 2D array arr = np.arange(10).reshape(2, 5) print("\narr : ", arr) # Maximum and minimum of the flattened array print("\nMax of arr, axis = None : ", np.amax(arr)) print("\nMin of arr, axis = None : ", np.amin(arr)) # Maxima and minima along the first axis # axis 0 means vertical print("Max of arr, axis = 0 : ", np.amax(arr, axis = 0)) print("Min of arr, axis = 0 : ", np.amin(arr, axis = 0)) # Maxima and minima along the second axis # axis 1 means horizontal print("Max of arr, axis = 1 : ", np.amax(arr, axis = 1)) print("Min of arr, axis = 1 : ", np.amin(arr, axis = 1))
Output:
arr : [0 1 2 3 4 5 6 7 8 9] Max of arr : 9 Min of arr : 0 arr : [[0 1 2 3 4] [5 6 7 8 9]] Max of arr, axis = None : 9 Min of arr, axis = None : 0 Max of arr, axis = 0 : [5 6 7 8 9] Min of arr, axis = 0 : [0 1 2 3 4] Max of arr, axis = 1 : [4 9] Min of arr, axis = 1 : [0 5]
In the code above we have used 2 new functions:
- Numpy.amax()
It is used to calculate the value of the maximum in an array. However, if the axis is mentioned it will find the maximum value along the mentioned axis.
Syntax of NumPy.amax() :
numpy.amax(arr, axis = None, out = None, keepdims = <class numpy._globals._NoValue>)
- Numpy.amin()
It is used to calculate the value of the minimum in an array. Although if the axis is mentioned it will find the minimum value along the mentioned axis.
Syntax of NumPy.amin() :
numpy.amin(arr, axis = None, out = None, keepdims = <class numpy._globals._NoValue>)
Parameters:
- Arr: It is the input data in the form of an array.
- Axis: It specifies the axis along which we want to calculate the maximum value.
- Out: It is an array in which the result will be stored. It is optional.
- Keepdims: If set to true, the axes which are reduced will be left in the result as dimensions size 1.
Leave a Reply