# [Solved] Efficiently create adjacency matrix from network graph (vice versa) Python NetworkX

I’m trying to get into creating network graphs and generating sparse matrices from them. From the wikipedia `Laplacian matrix` example, I decided to try and recreate the following network graph using `networkx` How can one EFFICIENTLY convert between an `adjacency matrix` and a `network graph`?

For example, if I have a network graph, how can I quickly convert it to an adjacency matrix and if I have an adjacency graph how can I efficiently convert it to a network graph.

Below is my code for doing it and I feel like it’s pretty inefficient for larger networks.

``````#!/usr/bin/python

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
import pandas as pd

%matplotlib inline

labels = range(1,7)

#   1  2  3  4  5  6
#1  0  1  0  0  1  0
#2  1  0  1  0  1  0
#3  0  1  0  1  0  0
#4  0  0  1  0  1  1
#5  1  1  0  1  0  0
#6  0  0  0  1  0  0

#Network graph
G = nx.Graph()

#Connect nodes
if node == 1:

#Draw graph
nx.draw(G,with_labels = True)

#DRAWN GRAPH MATCHES THE GRAPH FROM WIKI

DF_re = pd.DataFrame(np.zeros([len(G.nodes()),len(G.nodes())]),index=G.nodes(),columns=G.nodes())
for col_label,row_label in G.edges():
DF_re.loc[col_label,row_label] = 1
DF_re.loc[row_label,col_label] = 1
print G.edges()
#[(1, 2), (1, 5), (2, 3), (2, 5), (3, 4), (4, 5), (4, 6)]

print DF_re
#   1  2  3  4  5  6
#1  0  1  0  0  1  0
#2  1  0  1  0  1  0
#3  0  1  0  1  0  0
#4  0  0  1  0  1  1
#5  1  1  0  1  0  0
#6  0  0  0  1  0  0
``````
Solution #1:

How to convert from graph to adjacency matrix:

``````import scipy as sp
import networkx as nx
G=nx.fast_gnp_random_graph(100,0.04)
``````

Here’s the documentation.

And from adjacency matrix to graph:

``````H=nx.Graph(adj_matrix)  #if it's directed, use H=nx.DiGraph(adj_matrix)
``````

Here’s the documentation.

Solution #2:

I was confronted with the same problem, and found a solution.
We can use the function from_numpy_matrix, which is depicted in official website http://networkx.github.io/documentation/networkx-1.7/reference/generated/networkx.convert.from_numpy_matrix.html.
Pay attention that the input data usually needs to be modified by numpy.matrix().
The example given is that:

``````    import numpy
A=numpy.matrix([[1,1],[2,1]])
G=nx.from_numpy_matrix(A)
``````

It’s really useful.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .