Python 当 x 和 y 值作为 numpy 数组给出时,查找所有局部最大值和最小值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31070563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:26:29  来源:igfitidea点击:

Find all local Maxima and Minima when x and y values are given as numpy arrays

pythonnumpyderivative

提问by prtkp

I have two arrays xand yas :

我有两个数组xyas :

x = np.array([6, 3, 5, 2, 1, 4, 9, 7, 8])
y = np.array([2, 1, 3, 5, 3, 9, 8, 10, 7])

I am finding index of local minima and maxima as follows:

我正在查找局部最小值和最大值的索引如下:

sortId = np.argsort(x)
x = x[sortId]
y = y[sortId]
minm = np.array([])
maxm = np.array([])
while i < y.size-1:
   while(y[i+1] >= y[i]):
      i = i + 1

   maxm = np.insert(maxm, 0, i)
   i++
   while(y[i+1] <= y[i]):
      i = i + 1

   minm = np.insert(minm, 0, i)
   i++

What is the problem in this code? The answer should be index of minima = [2, 5, 7]and that of maxima = [1, 3, 6].

这段代码有什么问题?答案应该是minima = [2, 5, 7]和 的索引maxima = [1, 3, 6]

采纳答案by Cleb

You do not need this whileloop at all. The code below will give you the output you want; it finds all local minima and all local maxima and stores them in minmand maxm, respectively. Please note: When you apply this to large datasets, make sure to smooth the signals first; otherwise you will end up with tons of extrema.

你根本不需要这个while循环。下面的代码会给你你想要的输出;它找到所有局部最小值和所有局部最大值,并将它们分别存储在minm和 中maxm。请注意:当您将此应用于大型数据集时,请确保先平滑信号;否则你最终会得到大量的极值。

import numpy as np
from scipy.signal import argrelextrema
import matplotlib.pyplot as plt

x = np.array([6, 3, 5, 2, 1, 4, 9, 7, 8])
y = np.array([2, 1, 3 ,5 ,3 ,9 ,8, 10, 7])

# sort the data in x and rearrange y accordingly
sortId = np.argsort(x)
x = x[sortId]
y = y[sortId]

# this way the x-axis corresponds to the index of x
plt.plot(x-1, y)
plt.show()
maxm = argrelextrema(y, np.greater)  # (array([1, 3, 6]),)
minm = argrelextrema(y, np.less)  # (array([2, 5, 7]),)

This should be far more efficient than the above whileloop.

这应该比上面的while循环更有效。

The plot looks like this; I shifted the x-values so that they correspond to the returned indices in minmand maxm):

情节是这样的;我移动了 x 值,使它们对应于minmmaxm) 中返回的索引:

enter image description here

enter image description here

As of SciPy version 1.1, you can also use find_peaks:

从 SciPy 1.1 版开始,您还可以使用find_peaks

from scipy.signal import find_peaks

peaks, _ = find_peaks(y)

# this way the x-axis corresponds to the index of x
plt.plot(x-1, y)
plt.plot(peaks, y[peaks], "x")
plt.show()

That yields

这产生

enter image description here

enter image description here

The nice thing is, that you can now also easily also set a minimum peak height (e.g. 8):

好消息是,您现在还可以轻松设置最小峰高(例如 8):

peaks, _ = find_peaks(y, height=8)

# this way the x-axis corresponds to the index of x
plt.plot(x-1, y)
plt.plot(peaks, y[peaks], "x")
plt.show() 

enter image description here

enter image description here

Note that now the first peak is excluded as its height is below 8.

请注意,现在第一个峰被排除在外,因为它的高度低于 8。

Furthermore, you can set also the minimal distance between peaks (e.g. 5):

此外,您还可以设置峰值之间的最小距离(例如 5):

peaks, _ = find_peaks(y, distance=5)

# this way the x-axis corresponds to the index of x
plt.plot(x-1, y)
plt.plot(peaks, y[peaks], "x")
plt.show()

enter image description here

enter image description here

Now the middle peak is excluded as its distance to the other two peaks is less than 5.

现在中间的峰被排除在外,因为它与其他两个峰的距离小于 5。

回答by Geeocode

This will work fine.

这将正常工作。

Python uses +=instead of ++.

Python 使用+=代替++.

Before you use iin a while loop you have to assign some value - in this case 0 - , this way initializing it to avoid error.

在使用iwhile 循环之前,您必须分配一些值 - 在本例中为 0 - ,这样初始化它以避免错误。

import numpy as np

x=np.array([6,3,5,2,1,4,9,7,8])
y=np.array([2,1,3,5,3,9,8,10,7])


sortId=np.argsort(x)
x=x[sortId]
y=y[sortId]
minm = np.array([])
maxm = np.array([])
i = 0
while i < y.size-1:
   while(y[i+1] >= y[i]):
      i+=1

   maxm=np.insert(maxm,0,i)
   i+=1
   while(y[i+1] <= y[i]):
      i+=1

   minm=np.insert(minm,0,i)
   i+=1

print minm, maxm

回答by prtkp

x=np.array([6,3,5,2,1,4,9,7,8])
y=np.array([2,1,3,5,7,9,8,10,7])

sort_idx = np.argsort(x)
y=y[sort_idx]
x=x[sort_idx]
minm=np.array([],dtype=int)
maxm=np.array([],dtype=int)
length = y.size
i=0

while i < length-1:
    if i < length - 1:
        while i < length-1 and y[i+1] >= y[i]:
            i+=1

        if i != 0 and i < length-1:
            maxm = np.append(maxm,i)

        i+=1

    if i < length - 1:
        while i < length-1 and y[i+1] <= y[i]:
            i+=1

        if i < length-1:
            minm = np.append(minm,i)
        i+=1


print minm
print maxm

minmand maxmcontain indices of minima and maxima, respectively.

minm并分别maxm包含最小值和最大值的索引。