I have a csv file of nodes and a csv file of edges - all the nodes are STRING. I need help please for how can I build an adjacency matrix of this graph in python?
Example of the data:
Nodes csv:
a
b
c
d
Edges csv:
a,b
b,c
a,c
d,a
b,d
I want it to be presented as an adjacency matrix:
a b c d
a 0 1 1 1
b 1 0 1 1
c 1 1 0 0
d 1 1 0 0
Thank you!
Ok: assuming your nodes and edges have been converted to lists as follows, this works (as you can see, the code is self-explanatory):
nodes = ['a','b','c','d']
edges = [('a','b'),('b','c'),('a','c'),('d','a'),('b','d')]
import numpy as np
n = len(nodes)
matrix = np.zeros((n,n), dtype=int)
for i in range(n):
for j in range(n):
if (nodes[i],nodes[j]) in edges or (nodes[j],nodes[i]) in edges:
matrix[i,j] = matrix[j,i] = 1