简体   繁体   中英

Convert multilevel dictionary into a network graph in Python

I am stuck with a strange issue. I am reading data from a CSV file and converting it into a multi-level dictionary.

CSV Format: I have a total of 1,500 rows in my CSV file, see the format below.

1-103rd Street,1-96th Street,2327.416174
1-116th Street–Columbia University,1-Cathedral Parkway–110th Street,2327.416174
1-125th Street,1-116th Street–Columbia University,2327.416174
1-137th Street–City College,1-125th Street,2327.416174
1-145th Street,1-137th Street–City College,2327.416174
1-14th Street,1-Christopher Street–Sheridan Square,2327.416174

In the above file, the first column denotes a source station, the second column denotes a destination station, and the third column provides the distance between them.

I will have to apply Dijkstra's Algorithm to find the shortest distance between two stations, and for that I need to convert the whole CSV file into a weighted graph, in which each station is a node and the distance between them is the weight of the edge.

My approach:

First I am reading each row from the CSV file and converting it into a multi-level dictionary. I am getting a proper dictionary for this. Below is my code.

my_dict = {}

with open('final_subway_data.csv') as f_input:
    for row in csv.reader(f_input):
        my_dict[row[0]] = {row[1]: row[2]}

Now I need to convert this newly created dictionary into a graph in order to apply Dijkstra's Algorithm. For that I am using this code:

G = nx.from_dict_of_dicts(my_dict)

But I am getting an error saying "TypeError: Input graph is not a networkx graph type" .

Please help me. How can I convert the whole CSV file into a graph so I can apply Dijkstra's Algorithm to find a shortest distance between any two stations.

I'm not super familiar with NetworkX, but I'd do the following using pandas and nx.from_pandas_dataframe() .

import pandas as pd
import networkx as nx

df = pd.read_csv('csvpath.csv', names=['origin', 'dest', 'dist'])

g = nx.from_pandas_dataframe(df, source='origin', target='dest', edge_attr='dist')

g['1-103rd Street']['1-96th Street']['dest']
# 2327.416174

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM