Numpy 二维数组 - select 个没有 for 循环的多个元素

Numpy 2d array - select multiple elements without a for loop

我维护了一些代码,我 运行 处理了类似的东西:

    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}shape mismatch: indexing arrays could not be broadcast together with shapes (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]

按预期工作,不再循环