Can you suggest a module function from numpy/scipy that can find local maxima/minima in a 1D numpy array? Obviously the simplest approach ever is to have a look at the nearest neighbours, but I would like to have an accepted solution that is part of the numpy distro.
signal module that can be used to find local minima and maxima in an array/matrix. Function argrelmin() is used to calculate the relative minima of data. Similarly, argrelmax() is used to calculate the relative maxima of data. These functions return the indices of local minima/maxima in the data.
Approach: The idea is to iterate over the given array arr[] and check if each element of the array is smallest or greatest among their adjacent element. If it is smallest then it is local minima and if it is greatest then it is local maxima.
One dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple.
In SciPy >= 0.11
import numpy as np from scipy.signal import argrelextrema x = np.random.random(12) # for local maxima argrelextrema(x, np.greater) # for local minima argrelextrema(x, np.less)
Produces
>>> x 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]) >>> argrelextrema(x, np.greater) (array([1, 5, 7]),) >>> argrelextrema(x, np.less) (array([4, 6, 8]),)
Note, these are the indices of x that are local max/min. To get the values, try:
>>> x[argrelextrema(x, np.greater)[0]]
scipy.signal
also provides argrelmax
and argrelmin
for finding maxima and minima respectively.
If you are looking for all entries in the 1d array a
smaller than their neighbors, you can try
numpy.r_[True, a[1:] < a[:-1]] & numpy.r_[a[:-1] < a[1:], True]
You could also smooth your array before this step using numpy.convolve()
.
I don't think there is a dedicated function for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With