Reputation: 693
I'm trying to get through a toy example of building an adjacency matrix from a list, but already I can't quite figure it out. I am thinking in terms of .loc() but I'm not sure how to index correctly.
{'nodes':['A', 'B', 'C', 'D', 'E'],
'edges':[('A', 'B'), ('A', 'D'), ('B', 'C'), ('B', 'E'), ('C', 'D'),
('D', 'E'), ('E', 'A'),('E', 'B'), ('E', 'C')]}
I've started to build the matrix with:
n = len(graph['nodes'])
adj_matr = pd.DataFrame(0, columns = graph['nodes'], index = graph['edges'])
but now I'm not sure how to fill it in. I think there's an easy one liner, maybe with a list comprehension?
Expected output:
A B C D E
A 0 1 0 1 0
B 0 0 1 0 1
C 0 0 0 1 0
D 0 0 0 0 1
E 1 1 1 0 0
Upvotes: 4
Views: 2101
Reputation: 88305
A simple way to obtain the adjacency matrix is by using NetworkX
d = {'nodes':['A', 'B', 'C', 'D', 'E'],
'edges':[('A', 'B'), ('A', 'D'), ('B', 'C'), ('B', 'E'), ('C', 'D'),
('D', 'E'), ('E', 'A'),('E', 'B'), ('E', 'C')]}
It appears that from your adjacency matrix the graph is directed. You can create a directed graph as shown bellow and define its nodes and edges from the dictionary with:
import networkx as nx
g = nx.DiGraph()
g.add_nodes_from(d['nodes'])
g.add_edges_from(d['edges'])
And then you can obtain the adjacency matrix as a dataframe with nx.to_pandas_adjacency
:
nx.to_pandas_adjacency(g)
A B C D E
A 0.0 1.0 0.0 1.0 0.0
B 0.0 0.0 1.0 0.0 1.0
C 0.0 0.0 0.0 1.0 0.0
D 0.0 0.0 0.0 0.0 1.0
E 1.0 1.0 1.0 0.0 0.0
Upvotes: 3
Reputation: 1286
For a directed graph you can use:
df = pd.DataFrame(graph['edges'], columns=['From', 'To'])
df['Edge'] = 1
adj = df.pivot(index='From', columns='To', values='Edge').fillna(0)
Upvotes: 1
Reputation: 5344
for undirected graph
graph = {'nodes': ['A', 'B', 'C', 'D', 'E'],
'edges': [('A', 'B'), ('A', 'D'), ('B', 'C'), ('B', 'E'), ('C', 'D'),
('D', 'E'), ('E', 'A'), ('E', 'B'), ('E', 'C')]}
n = len(graph['nodes'])
adj_matr = pd.DataFrame(0, columns=graph['nodes'], index=graph['nodes'])
for i in graph['edges']:
adj_matr.at[i[0], i[1]] = 1
adj_matr.at[i[1], i[0]] = 1
print(adj_matr)
A B C D E
A 0 1 0 1 1
B 1 0 1 0 1
C 0 1 0 1 1
D 1 0 1 0 1
E 1 1 1 1 0
for directed graph:
graph = {'nodes': ['A', 'B', 'C', 'D', 'E'],
'edges': [('A', 'B'), ('A', 'D'), ('B', 'C'), ('B', 'E'), ('C', 'D'),
('D', 'E'), ('E', 'A'), ('E', 'B'), ('E', 'C')]}
n = len(graph['nodes'])
adj_matr = pd.DataFrame(0, columns=graph['nodes'], index=graph['nodes'])
print(adj_matr)
for i in graph['edges']:
adj_matr.at[i[0], i[1]] = 1
# adj_matr.at[i[1], i[0]] = 1
print(adj_matr)
A B C D E
A 0 1 0 1 0
B 0 0 1 0 1
C 0 0 0 1 0
D 0 0 0 0 1
E 1 1 1 0 0
Upvotes: 1