繁体   English   中英

来自包含节点和连接的文本文件的邻接矩阵 python

[英]Adjacency matrix from text file containing nodes and connections python

我有一个包含矩阵边缘的文件。 例如,从文件生成的邻接矩阵中的位置 (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 

output 应该是:

[[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.]]

谢谢你!!

你可以试试这个:

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]]

暂无
暂无

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

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