Home > Article > Backend Development > How can SciPy's `argrelextrema` function be used to effectively detect local maxima and minima in 1D Numpy arrays?
Finding local maxima and minima in 1D numerical arrays is a common task in data analysis. While simplistic approaches might involve comparing an element to its neighbors, it is advisable to use established algorithms as part of popular scientific computing libraries.
One such library is SciPy, which offers the argrelextrema function for locating local extrema in 1D arrays. This function can work with both maxima and minima, making it a versatile solution. Here's how to use it:
import numpy as np from scipy.signal import argrelextrema # Example 1D array x = np.random.random(12) # Detect local maxima maxima_indices = argrelextrema(x, np.greater) # Detect local minima minima_indices = argrelextrema(x, np.less)
The argrelextrema function returns a tuple containing an array with the indices of local extrema. Note that these are just the indices in the input array, not the actual values. To obtain the corresponding values, use:
maxima_values = x[maxima_indices[0]] minima_values = x[minima_indices[0]]
For convenience, SciPy also provides the standalone functions argrelmax and argrelmin for finding maxima and minima separately.
The above is the detailed content of How can SciPy's `argrelextrema` function be used to effectively detect local maxima and minima in 1D Numpy arrays?. For more information, please follow other related articles on the PHP Chinese website!