Home > Article > Backend Development > How to Find Local Maxima and Minima in a 1D Numpy Array?
Utilizing Numpy's SciPy Module to Locate Local Maxima and Minima in a 1D Numpy Array
Seeking a Numpy or SciPy module function capable of identifying local maxima and minima within a 1D Numpy array, we can explore a proven solution employed within the Numpy distribution.
Solution Using SciPy's Extrema Detection Functions
For instances where your SciPy installation is version 0.11 or later, you can leverage the argrelextrema function:
import numpy as np from scipy.signal import argrelextrema x = np.random.random(12) # Detect local maxima maxima_indices = argrelextrema(x, np.greater) # Detect local minima minima_indices = argrelextrema(x, np.less)
This script generates arrays containing the indices of local maxima or minima. To retrieve the corresponding values, utilize:
maxima_values = x[maxima_indices[0]] minima_values = x[minima_indices[0]]
Alternative Options from SciPy.Signal
SciPy.signal also offers dedicated functions for handling max and min detection:
Employ these methods for specific extraction of maxima or minima.
Example Output
For the example array [0.56660112, 0.76309473, 0.69597908, 0.38260156, 0.24346445, 0.56021785, 0.24109326, 0.41884061, 0.35461957, 0.54398472, 0.59572658, 0.92377974], the output indices of local maxima and minima are:
The above is the detailed content of How to Find Local Maxima and Minima in a 1D Numpy Array?. For more information, please follow other related articles on the PHP Chinese website!