我想恢复采样数据数组中的句点:
signal = [45, 46, -12, -12.5, 32, 35, 34, 25, 23, -23, -65, -3, 43, 23]
我想计算一段时间的大小。句号以正数开头,然后移至负数,然后返回正数。
例如:
period1=[45 46 -12 -12.5 32] # length=5
period2=[32 35 34 25 23 -23 -65 -3 43] # length=8
如何做到这一点?
答案 0 :(得分:1)
这里的技巧是使用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)