我试图从numpy
记录数组no1
中找到最接近于记录数组中的值的所有值no2
(记录数组具有不同数量的值)
可以说no1
有字段:
('electrode', 'i4'), ('no_of_interest_time', 'i4'), ('time', 'f8')
其中time
具体事件的时间和no_of_interest_time
索引事件应单独分析。每个事件都有一个这样的编号,并且多个事件可以共享相同的编号。electrode
保存记录事件的电极的索引(位置)。
no2
具有相同的字段,但拥有不同的事件。
对于 recarray 中的每个事件no2
,我想从no1
相同类型(no_of_interest_time
)和位置(electrode
)的 recarray 中找到最近的事件。
我可以使用 for 循环解决它的方式如下所示,但我正在寻找更优雅的解决方案:
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]
我将不胜感激任何建议。提前致谢!!