2012-11-26 77 views
2

密切元素我試圖找到所有從numpy記錄陣列no1這是最接近值REC陣列no2值(記錄陣列有不同數量的值)發現numpy的recarray

比方說no1有字段:

('electrode', 'i4'), ('no_of_interest_time', 'i4'), ('time', 'f8')

其中time是特定事件和應單獨分析no_of_interest_time指標事件的時間。每個事件都有一個這樣的號碼,多個事件可以共享相同的號碼。 electrode保存記錄事件的電極的指數(位置)。

no2具有相同的字段但包含不同的事件。

對於recarray no2每一個事件,我想找到同類型的(no_of_interest_time)和地點(electrode)的recarray no1最接近的事件。

我可以使用循環應該是這樣的解決問題的方法,但是我正在尋找更好的解決方案:

import numpy as np 

i_recarr1 = np.argsort(recarray1, order=['electrode', 'no_of_interest_time', 'time']) 
recarr1_sorted = recarray1[i_recarr1] 

i_recarr2 = np.argsort(recarray2, order=['electrode', 'no_of_interest_time', 'time']) 
recarr2_sorted = recarray2[i_recarr2] 

closest_events = recarr2_sorted.copy() 

for electr in np.unique(recarr2_sorted['electrode']): 
    # use only this electrode 
    recarr1_record = recarr1_sorted[recarr1_sorted['electrode'] == electr] 
    recarr1_record = recarr2_sorted[recarr2_sorted['electrode'] == electr] 

    for interest in np.unique(recarr2_record['no_of_interest_time']): 
     # use only this time of interest 
     recarr1_interest = recarr1_sorted[recarr1_record['no_of_interest_time'] == interest] 
     recarr2_interest = recarr1_sorted[recarr1_record['no_of_interest_time'] == interest] 

     for idx, event2 in np.enumerate(recarr2_interest['time']): 
      # loop through every event to find neighbours 
      selected_idx = (np.abs(recarr1_interest['time']-event2)).argmin() 
      closest_events[(closest_events['electrode'] == electr) & 
          (closest_events['no_of_interest_time']) == interest][idx] = recarr1_interest['time'][selected_idx] 

inverse_i = np.argsort(i_recarr2)  
closest_events[inverse_i] 

我會感謝任何意見。提前致謝!!

回答

2

如何:

closest_events = [] 
for t in no1: 
    #sort 
    i = np.argsort(np.abs(t['time']-no2['time'])) 
    # select only events with the same no_of_interest_time and electrode 
    i = i[(no2['electrode']==t['electrode']) & 
      (no2['no_of_interest_time']==t['no_of_interest_time'])] 
    closest = i[0] if len(i)>0 else np.nan 
    closest_events.append(closest) 

的想法是,在no1每一個事件,你先計算這一事件,並在no2所有事件之間的距離。接下來,您將從最短到最長的距離排序,並存儲索引(i在函數中)。從i您只選擇特定類型和位置的元素,最後您首先獲取其餘索引(如果該數組爲空,則返回NaN)。