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

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

    None of these solutions worked for me since I wanted to find peaks in the center of repeating values as well. for example, in

    ar = np.array([0,1,2,2,2,1,3,3,3,2,5,0])

    the answer should be

    array([ 3,  7, 10], dtype=int64)
    

    I did this using a loop. I know it's not super clean, but it gets the job done.

    def findLocalMaxima(ar):
    # find local maxima of array, including centers of repeating elements    
    maxInd = np.zeros_like(ar)
    peakVar = -np.inf
    i = -1
    while i < len(ar)-1:
    #for i in range(len(ar)):
        i += 1
        if peakVar < ar[i]:
            peakVar = ar[i]
            for j in range(i,len(ar)):
                if peakVar < ar[j]:
                    break
                elif peakVar == ar[j]:
                    continue
                elif peakVar > ar[j]:
                    peakInd = i + np.floor(abs(i-j)/2)
                    maxInd[peakInd.astype(int)] = 1
                    i = j
                    break
        peakVar = ar[i]
    maxInd = np.where(maxInd)[0]
    return maxInd 
    

提交回复
热议问题