這裏的訣竅是使用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