简体   繁体   English

在Python中将多级字典转换为网络图

[英]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文件中读取数据,并将其转换为多级字典。

CSV Format: I have a total of 1,500 rows in my CSV file, see the format below. CSV格式:CSV文件中总共有1,500行,请参见以下格式。

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. 我将必须应用Dijkstra算法来找到两个站点之间的最短距离,为此,我需要将整个CSV文件转换为加权图,其中每个站点都是一个节点,它们之间的距离就是边缘的权重。

My approach: 我的方法:

First I am reading each row from the CSV file and converting it into a multi-level dictionary. 首先,我从CSV文件中读取每一行,并将其转换为多级字典。 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. 现在,我需要将此新创建的字典转换为图形,以应用Dijkstra的算法。 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" . 但是我收到一条错误消息,提示"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. 如何将整个CSV文件转换为图形,以便应用Dijkstra的算法来查找任何两个站之间的最短距离。

I'm not super familiar with NetworkX, but I'd do the following using pandas and nx.from_pandas_dataframe() . 我对NetworkX不太熟悉,但是我会使用pandas和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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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