我维护了一些代码,并遇到类似的问题:
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]
会导致:
{IndexError}形状不匹配:索引数组无法与形状一起广播(4,)(8,)
答案 0 :(得分:0)
知道了 - 我需要将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]
按预期工作,不再循环