Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding local maxima/minima with Numpy in a 1D numpy array

Tags:

python

numpy

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.

like image 260
Navi Avatar asked Jan 07 '11 11:01

Navi


People also ask

How do you find the local minima and maxima in Python?

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.

How do you find the local maxima and local minima in an array?

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.

What is 1d array in Numpy?

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.


2 Answers

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.

like image 71
danodonovan Avatar answered Sep 24 '22 09:09

danodonovan


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.

like image 37
Sven Marnach Avatar answered Sep 24 '22 09:09

Sven Marnach