2017-02-20 54 views
-1

欲恢复在采样数据的阵列的时期:计算符号变换之间的距离在采样数据

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

您滥用单词“cycle”。这意味着非常不同的东西。 – DyZ

+1

你尝试了什么? –

+0

描述你观察到的一些想法和问题。这是一个相当简单的任务。 – sascha

回答

0

这里的诀窍是使用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) 
+0

这是工作谢谢 –