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

后端 未结 12 1885
迷失自我
迷失自我 2020-11-22 15:13

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 neare

12条回答
  •  情书的邮戳
    2020-11-22 15:46

    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.

提交回复
热议问题