Search code examples
pythonpandasgraphdijkstra

Shortest path from A to B in a weighted and directed 2D pandas csv graph


I have a weighted graph represented by 2D n x n matrix that I created using pandas and saved as a csv file

The indices and column headers are numbers that represent the nodes. the edges are weights connecting two nodes

for example: {1232: {1232: inf, 2342: 12, 45654: inf, 45678: 21}} and so on

I want to implement shortestRoute algorithm that will return the nodes of the shortest (smallest total weight) path from node a to b.

So it will return 1232 -> 2345 -> 45678

I know i can implement Dijkstra’s to get the smallest weight, but not sure how to get the path

inf refers to two nodes that are not connected by an edge


Solution

  • Making a small example using your data + an extra edge.

    import pandas as pd
    import networkx as nx
    
    so = pd.DataFrame({
        "source": [1232, 1232 , 1232, 2345 ],
        "target": [2342, 45678, 2345, 45678],
        "weight": [12  , 21   ,    1,      1]
    })
    
    G = nx.from_pandas_edgelist(so, source="source", target="target", edge_attr="weight")
    
    # added since `nx.draw_networkx_edge_labels` requires `pos`
    pos = nx.spring_layout(G)
    
    nx.draw(G, pos=pos, with_labels=True, node_size=500)
    
    # taken from https://stackoverflow.com/a/67145811/6509519
    nx.draw_networkx_edge_labels(G, pos=pos);
    

    network

    nx.shortest_path(G, source=1232, target=45678, weight="weight", method="dijkstra")
    # >>> [1232, 2345, 45678]