【问题标题】:Adjacency matrix from text file containing nodes and connections python来自包含节点和连接python的文本文件的邻接矩阵
【发布时间】:2021-04-10 01:12:26
【问题描述】:

我有一个包含矩阵边缘的文件。例如,从文件生成的邻接矩阵中的位置 (1, 2) 是 2,因为对 1 2 在图中出现了两次。

我需要使用 python 从中创建一个邻接矩阵,但我不确定该怎么做。

文件是:

0 1 
1 2  1 2  1 3  1 3  1 4 
2 3 
3 0 
4 0  4 2 

输出应该是:

[[0. 1. 0. 0. 0.]
[0. 0. 2. 2. 1.]
[0. 0. 0. 1. 0.]
[1. 0. 0. 0. 0.]
[1. 0. 1. 0. 0.]]

谢谢!!

【问题讨论】:

  • 为文件中的每一行创建一个新行,然后使用该索引的计数更新该行的索引。

标签: python list matrix adjacency-matrix


【解决方案1】:

你可以试试这个:

s = """
0 1 
1 2  1 2  1 3  1 3  1 4 
2 3 
3 0 
4 0  4 2 
"""

import re
import numpy as np

# get an array with vertices of edges
a = np.array(re.findall(r"(\d+) (\d+)", s)).astype(int)
# compute the adjacency matrix
np.add.at(adj := np.zeros((n := a.max() + 1, n), dtype=int), tuple(a.T), 1)
print(adj)

它给出:

[[0 1 0 0 0]
 [0 0 2 2 1]
 [0 0 0 1 0]
 [1 0 0 0 0]
 [1 0 1 0 0]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多