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

后端 未结 12 1839
迷失自我
迷失自我 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:44

    For curves with not too much noise, I recommend the following small code snippet:

    from numpy import *
    
    # example data with some peaks:
    x = linspace(0,4,1e3)
    data = .2*sin(10*x)+ exp(-abs(2-x)**2)
    
    # that's the line, you need:
    a = diff(sign(diff(data))).nonzero()[0] + 1 # local min+max
    b = (diff(sign(diff(data))) > 0).nonzero()[0] + 1 # local min
    c = (diff(sign(diff(data))) < 0).nonzero()[0] + 1 # local max
    
    
    # graphical output...
    from pylab import *
    plot(x,data)
    plot(x[b], data[b], "o", label="min")
    plot(x[c], data[c], "o", label="max")
    legend()
    show()
    

    The +1 is important, because diff reduces the original index number.

提交回复
热议问题