Finding Local Maxima/Minima in a 1D Numpy Array with Numpy
Identifying local maxima and minima in a 1D numpy array is a common task in signal processing and data analysis. While a simple approach involves comparing an element with its nearest neighbors, a more robust solution is sought within the numpy/scipy libraries.
Solution Using SciPy's argrelextrema
In SciPy versions 0.11 onwards, the argrelextrema function provides an efficient way to find local extrema in a 1D array:
import numpy as np from scipy.signal import argrelextrema x = np.random.random(12) # Find indices of local maxima maxima_indices = argrelextrema(x, np.greater) # Find indices of local minima minima_indices = argrelextrema(x, np.less)
The function returns tuples containing indices of elements that are local maxima or minima:
>>> argrelextrema(x, np.greater) (array([1, 5, 7]),) >>> argrelextrema(x, np.less) (array([4, 6, 8]),)
To obtain the actual values at these local extrema:
>>> x[argrelextrema(x, np.greater)[0]]
Additional Functions in SciPy
In addition to argrelextrema, SciPy provides specialized functions for finding only maxima or minima:
The above is the detailed content of How to Find Local Maxima and Minima in a 1D Numpy Array Using SciPy?. For more information, please follow other related articles on the PHP Chinese website!