2017-02-20 51 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

這是工作謝謝 –