Home >Backend Development >Python Tutorial >How to Find Local Maxima and Minima in 1D Numpy Arrays?
Locating Local Maxima and Minima in 1D Arrays with Numpy
Identifying local maxima and minima in 1D numpy arrays is a common task in various applications. While checking adjacent elements is an intuitive approach, Numpy offers a more comprehensive and reliable solution.
Numpy's argrelextrema Function
In SciPy 0.11 and later, the argrelextrema function can efficiently find both local maxima and minima in a 1D numpy array. It takes two arguments:
Usage:
To find local maxima, use:
argrelextrema(x, np.greater)
To find local minima, use:
argrelextrema(x, np.less)
Output
The argrelextrema function returns a tuple containing a single-dimensional array of indices corresponding to the extrema. These indices can be used to access the values of the local maxima or minima.
Example:
Consider the following numpy array:
x = np.random.random(12)
Finding the indices of local maxima and minima:
max_indices = argrelextrema(x, np.greater)[0] min_indices = argrelextrema(x, np.less)[0]
Retrieving the actual values:
max_values = x[max_indices] min_values = x[min_indices]
By using Numpy's argrelextrema function, you can accurately identify local maxima and minima in 1D numpy arrays, simplifying this common task.
The above is the detailed content of How to Find Local Maxima and Minima in 1D Numpy Arrays?. For more information, please follow other related articles on the PHP Chinese website!