代码之家  ›  专栏  ›  技术社区  ›  Mr_and_Mrs_D

numpy二维数组-选择多个没有for循环的元素[关闭]

  •  -1
  • Mr_and_Mrs_D  · 技术社区  · 6 年前

    我维护了一些代码,我遇到了如下问题:

        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,)一起广播

    1 回复  |  直到 6 年前
        1
  •  0
  •   Mr_and_Mrs_D    6 年前

    明白了-我要通过 some_indexes 作为列表列表,如此麻木地将每个列表广播到 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]
    

    按预期工作,不再循环