2016-04-29 90 views
3

我有這個風力數據集,它包含m/s的風速,我想計算時間序列中非零數據的週期。np.where()不返回numpy python中的預期索引

  • 非零數據的每個週期都會計爲一次「天氣事件」。

  • 我也想知道那些事件在數據集(即指數)內的位置。要做到這一點

的一種方法是計算各組非零數據的前第一個0的系列,以確定事件的數量,然後通過一個將每個索引值,以獲得事件的位置。

# create mock data. 
d=np.zeros([209]) 
d1=np.random.randn(189) 
d2=np.zeros(9) 
d3=np.random.randn(281) 
d4=np.zeros(27) 
d5=np.random.randn(21) 
d6=np.zeros(155) 
d7=np.random.randn(58) 
mock_data=np.concatenate((d,d1,d2,d3,d4,d5,d6,d7),axis=0) 


indices=np.squeeze(np.array(np.where(mock_data!=0))) # Returns the position vector of every non-zero in the record. 

# create a vector to store the positions of the previous zero before each SAW event. 
dummy=np.zeros(0) 
for i in range(len(indices)): 
    dummy=np.append(dummy,indices[i]-1) 
dummy=dummy.astype(int) 
dummy=np.int64(dummy) 

zerovalue=np.squeeze(np.array(np.where(mock_data[dummy]==0))) # Should return the position of the previous zero before each SAW event. 

# Add 1 to each value in zerovalue 
new_index=np.zeros(0) 
for i in range(len(zerovalue)): 
    new_index=np.append(date_index,zerovalue[i]+1) 

但是,我遇到了問題np.where()沒有返回我期待的指數。它不是返回指示非零數據組的第一個值在哪裏的索引,而是返回看似隨機的索引。

例如,第一個索引應該是209,但我得到0.任何幫助,非常感謝。

+0

你總是第一個索引越來越0?你有什麼其他價值? –

回答

3

讓我們先來清潔您的代碼開始上升的:

  1. 你不需要擠壓和數組類型轉換;剛剛從where結果提取的第一個元素:

    indices = np.where(mock_data)[0] 
    # array([209, 210, 211, 212, 213, ... 945, 946, 947, 948]) 
    
  2. NumPy的可以做量化的計算,所以你不需要循環創建dummy

    dummy = indices - 1 
    
  3. 對於zero_value你也可以省略擠壓和數組轉換;但這個時候你要零元素,因此比較有留:

    zerovalue = np.where(mock_data[dummy] == 0)[0] 
    # array([ 0, 189, 470, 491]) 
    
  4. 並再次NumPy的向量化的計算:所以現在

    new_index = zerovalue + 1 
    

的解釋,也許你會發現出錯的地方:

  • indices是你測量一些風的點。
  • dummy是你再次測量風前(您檢查在該指數在你開始沒有可測量的風后測量風)天(最後一天無風)
  • zerovalue累計天與測風。既然你停止了風,你最終會忽略風的最後幾天。

如果你想找到風的第一天至少休息一天後,沒有你需要保持你的陣列結構風:

mock_data != 0 # boolean array where you measured wind 
np.diff(mock_data != 0) # boolean array which has True between no-wind and wind. 
np.where(np.diff(mock_data != 0))[0] # array with indexes where it changed 
# array([208, 397, 406, 687, 714, 735, 890], dtype=int64) 

因爲你也改變這並不是最終結果從颳風不颳風天,所以你放棄每第二個元素

np.where(np.diff(mock_data != 0))[0][0::2] 
# array([208, 406, 714, 890], dtype=int64) 

因此,所有的計算可以在一行來完成:

np.where(np.diff(mock_data != 0))[0][0::2] + 1 # with the +1 
# array([209, 407, 715, 891], dtype=int64) 

,如果你有興趣在大風天收盤僅與[1::2]切它:

np.where(np.diff(mock_data != 0))[0][1::2] + 1 
# array([398, 688, 736], dtype=int64)