向量化嵌套的 for 循环

时间:2021-05-07 12:06:03

标签: python-3.x numpy for-loop vectorization osmnx

我有 2 个 for 循环,我想用矢量化对其进行修改,因为 2 个 for 循环需要很长时间才能完成。

先决条件:

import osmnx as ox
ox.config(use_cache=True, log_console=True)

# Create Graph of any city
place_name = "any city in the world" ### Enter your city
G = ox.graph_from_address(place_name, dist=2500, network_type="drive" )


and the dfGrid looks like this and has 2345 entries:

enter image description here

我要转换的代码:

for i in range(2345):
    for j in range(2345):
        if j == i:
            continue
        else:
            
            # From
            start = (dfGrid['Y_Centroid'].iloc[i], dfGrid['X_Centroid'].iloc[i])   

            # To
            end = (dfGrid['Y_Centroid'].iloc[j], dfGrid['X_Centroid'].iloc[j])  

            # Get the Nearest Node
            start_node = ox.get_nearest_node(G, start)
            end_node = ox.get_nearest_node(G, end)

            # Calculate the shortest path
            route = nx.shortest_path(G, start_node, end_node, 
            weight='travel_time')

            # Plot the route and street networks
            ox.plot_graph_route(G, route, route_linewidth=6, node_size=0, 
            bgcolor='k');

我听说 numpy 在这种情况下可以派上用场。

1 个答案:

答案 0 :(得分:2)

并非所有问题都可以矢量化。 Dijkstra 算法(用于最短路径计算)就是一个例子。但是,您的代码的其他部分可以矢量化或以其他方式提高效率,并且最短路径计算可以并行

  1. 将所有 iloc 代码移出 for 循环,因为 GeoPandas 可以获取值列表并根据它们进行选择。
  2. 将最近的节点代码移出 for 循环,因为最新的 OSMnx (v1.1.0) 具有矢量化的 nearest_nodes function
  3. 并行化您的最短路径求解,如 OSMnx usage examples 中所示,并在一切完成后绘制。