Numpy 2d 数组 - 选择多个没有 for 循环的元素



我维护一些代码,我遇到了类似的东西:

travel_time_vec = np.zeros(...)
for v in some_indexes: # some_indexes is a list of row indexes
traveltimes = traveltime_2d_array[v, list_of_column_indexes]
best_index = np.argmin(traveltimes)
travel_time_vec[v] = traveltimes[best_index]

我想放弃 for 循环并一次执行以下所有操作 - 但天真地要求traveltime_2d_array[some_indexes, list_of_column_indexes]结果:

{索引错误}形状不匹配:索引数组无法与形状一起广播 (4,( (8,(

知道了- 我需要将some_indexes作为列表列表传递,以便 numpy 将每个列表广播到list_of_column_indexes中的列。所以这个:

travel_time_vec = np.zeros(...)
# newaxis below tranforms [1, 2, 3] to [[1], [2], [3]]
traveltimes = traveltime_2d_array[np.array(some_indexes)[:, np.newaxis], 
list_of_column_indexes]
# get the index of the min time on each row
best_index = np.argmin(traveltimes, axis=1)
travel_time_vec[some_indexes] = traveltimes[:, best_index]

按预期工作,不再循环

相关内容

  • 没有找到相关文章

最新更新