SapZur
SapZur

Reputation: 13

Adjacency matrix with string nodes in Python

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!

Upvotes: 0

Views: 292

Answers (2)

Ykulvaarlck
Ykulvaarlck

Reputation: 1

here is a much more efficient solution:

import numpy as np

edges = np.array([['a','b'],['b','c'],['a','c'],['d','a'],['b','d']])

from_keys, fid = np.unique(edges[:, 0], return_inverse=True)
to_keys, tid = np.unique(edges[:, 1], return_inverse=True)

adjacency = np.zeros([len(from_keys), len(to_keys)], int)
adjacency[fid, tid] = 1

print(adjacency)

note that this calculates the directed adjacency matrix. if you want the undirected matrix, add the reverse edges to the input.

Upvotes: 0

Swifty
Swifty

Reputation: 3419

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

Upvotes: 0

Related Questions