这里的诀窍是使用numpy.diff()两次。第一个差异可以用来找到标志交叉点。第二个差异可以用来找到这些交叉点之间的距离。
代码:
import numpy as np
# put the data into a numpy array
signal = np.array(
[45, 46, -12, -12.5, 0, 32, 35, 34, 25, 23, -23, -65, -3, 43, 23])
# consider zeros to be negative, since we are looking for return to positive
signal[np.where(signal == 0.0)] = -1e-100
# find any returns to positive
return_to_positive = 1 + np.where(2 == np.diff(np.sign(signal)))[0]
# the periods are the distance between `return to positives`
periods = np.diff(return_to_positive)
输出:
>>> print(periods)
[8]
魔术解释:
我们首先需要确保有在出数据没有零点。这是因为我们想要清零过零点。因为我们希望第一个正值是周期的开始,所以将零设置为小于零。
# consider zeros to be negative, since we are looking for return to positive
signal[np.where(signal == 0.0)] = -1e-100
取出信号的符号,然后进行比较。任何地方这是2
是信号从负向正的地方。将1
添加到索引,因为前面的diff
从数组中删除了一个元素。 (附注,pandas
为您完成此)
# find the indices for any returns to positive
return_to_positive = 1 + np.where(2 == np.diff(np.sign(signal)))[0]
最后,采取指数之间的距离对于每个过零点,以获得时间。
# the periods are the distance between `return to positives`
periods = np.diff(return_to_positive)
您滥用单词“cycle”。这意味着非常不同的东西。 – DyZ
你尝试了什么? –
描述你观察到的一些想法和问题。这是一个相当简单的任务。 – sascha