create adjacency matrix networkx in python

You can create an adjacency matrix in Networkx using the nx.to_numpy_matrix() or nx.to_pandas_adjacency() functions as follows:

main.py
import networkx as nx

# create a directed graph
G = nx.DiGraph()

# add edges to the graph
G.add_edge('A', 'B')
G.add_edge('B', 'C')
G.add_edge('B', 'D')
G.add_edge('D', 'A')

# create an adjacency matrix
adj_matrix = nx.to_numpy_matrix(G)

print(adj_matrix)
260 chars
16 lines

This will output:

main.py
[[0. 1. 0. 0.]
 [0. 0. 1. 1.]
 [0. 0. 0. 0.]
 [1. 0. 0. 0.]]
61 chars
5 lines

If you want to create a pandas DataFrame from the adjacency matrix, use nx.to_pandas_adjacency() function:

main.py
import pandas as pd

# create a pandas dataframe from the adjacency matrix
adj_df = pd.DataFrame(adj_matrix, index=G.nodes(), columns=G.nodes())

print(adj_df)
160 chars
7 lines

This will output:

main.py
     A    B    C    D
A  0.0  1.0  0.0  0.0
B  0.0  0.0  1.0  1.0
C  0.0  0.0  0.0  0.0
D  1.0  0.0  0.0  0.0
110 chars
6 lines

Note: In this example, we have created a directed graph. If you have an undirected graph, you can use nx.to_numpy_matrix(G, nonedge=0) to get an adjacency matrix with zeros in non-existent edges.

gistlibby LogSnag