简体   繁体   English

从csv文件在python中创建邻接表

[英]Create an adjacency list in python from csv file

I am new to python. 我是python的新手。 I have a CSV file showing distance matrices and would like to construct an adjacency list using the information in the CSV, but I do not have an idea how to go about this task. 我有一个显示距离矩阵的CSV文件,并想使用CSV中的信息构造一个邻接表,但是我不知道如何执行此任务。

CSV dataset: CSV数据集:

在此处输入图片说明

I would like the distances to be the weights of the edges. 我希望距离成为边缘的权重。 Below is an example of my expected results: 以下是我预期结果的示例:

AdjList = {1: [{Node2:11242, node5:1511}], 2:[{Node6:1024, Node10:985}], etc. }

Without loss of generality, below is a solution via numpy and collections.defaultdict . 不失一般性,下面是通过numpycollections.defaultdict解决方案。

The result is a nested dictionary, where the outer keys are row numbers and inner keys are column numbers. 结果是一个嵌套字典,其中外键是行号,内键是列号。

The solution can be adapted to your problem and desired output. 该解决方案可以适应您的问题和所需的输出。 You may wish to look at pandas to extract row numbers, column names and data separately to use in the below algorithm. 您不妨查看一下pandas以分别提取行号,列名和数据,以在以下算法中使用。

from collections import defaultdict
import numpy as np

arr = np.array([[0, 134, 0, 451, 0],
                [234, 0, 4513, 0, 0],
                [0, 0, 132, 34, 0],
                [452, 562, 0, 0, 0]])

d = defaultdict(lambda: defaultdict(int))

for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        val = arr[i, j]
        if val != 0:
            d[i+1][j+1] = val

Result 结果

defaultdict(<function __main__.<lambda>>,
            {1: defaultdict(int, {2: 134, 4: 451}),
             2: defaultdict(int, {1: 234, 3: 4513}),
             3: defaultdict(int, {3: 132, 4: 34}),
             4: defaultdict(int, {1: 452, 2: 562})})

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

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