簡體   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