使用scipy.signal查找局部最大值

时间:2018-11-19 15:37:54

标签: python python-3.x scipy

我有64个整数值的1D数组(A)。如何使用56模块找到与值5010(分别为索引45scipy.signal)相对应的2个局部最大值?

起初我尝试导入

from scipy.signal import find_peaks

A
array([  0.,   1.,   3.,   8.,   6.,  16.,  29.,  29.,  47.,  42.,  56.,
    44.,  49.,  40.,  34.,  34.,  26.,  24.,  25.,  21.,  22.,  24.,
    34.,  17.,  17.,  29.,  24.,  26.,  13.,  25.,  16.,  19.,  19.,
    26.,  24.,  26.,  41.,  34.,  24.,  37.,  37.,  39.,  34.,  40.,
    45.,  50.,  28.,  45.,  43.,  46.,  47.,  41.,  30.,  23.,  19.,
    15.,   9.,  10.,   3.,   6.,   4.,   1.,   1.,   0.])

但是在进一步了解之前,我收到了错误消息

  

“ AttributeError:'模块'对象没有属性'find_peaks'”,

所以后来我尝试导入

from scipy import signal
peakind = signal.find_peaks_cwt(A, widths=32)

但随后我得到了错误消息

  

“ TypeError:'int'对象不可下标”。

即使我先做A.astype(np.int64),我仍然会收到此错误消息。

我不能在整数值数组上使用scipy.signal_find_peaks吗?

1 个答案:

答案 0 :(得分:1)

您可以按以下方式使用find_peaks(确保您使用的是SciPy> = 1.1):

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

A = np.array([0.,   1.,   3.,   8.,   6.,  16.,  29.,  29.,  47.,  42.,  56.,
    44.,  49.,  40.,  34.,  34.,  26.,  24.,  25.,  21.,  22.,  24.,
    34.,  17.,  17.,  29.,  24.,  26.,  13.,  25.,  16.,  19.,  19.,
    26.,  24.,  26.,  41.,  34.,  24.,  37.,  37.,  39.,  34.,  40.,
    45.,  50.,  28.,  45.,  43.,  46.,  47.,  41.,  30.,  23.,  19.,
    15.,   9.,  10.,   3.,   6.,   4.,   1.,   1.,   0.])

peaks, _ = find_peaks(A, distance=32)
print(peaks)
# This prints the desired indices [10 45]

plt.plot(A)
plt.plot(peaks, A[peaks], "x")
plt.show()

因此,您可以使用widths来定义两个峰之间的最小距离,而不必使用distance

这将绘图:

enter image description here

如您所见,只有两个所需的峰用x标记,所有其余的局部最大值都被忽略。

相关问题