Converting to and from other data formats

To NetworkX Graph

Functions to convert NetworkX graphs to and from other formats.

The preferred way of converting data to a NetworkX graph is through the graph constructor. The constructor calls the to_networkx_graph() function which attempts to guess the input type and convert it automatically.

Examples

Create a graph with a single edge from a dictionary of dictionaries

>>> d={0: {1: 1}} # dict-of-dicts single edge (0,1)
>>> G=nx.Graph(d)

See also

nx_agraph, nx_pydot

to_networkx_graph(data[, create_using, …])

Make a NetworkX graph from a known data structure.

Dictionaries

to_dict_of_dicts(G[, nodelist, edge_data])

Returns adjacency representation of graph as a dictionary of dictionaries.

from_dict_of_dicts(d[, create_using, …])

Returns a graph from a dictionary of dictionaries.

Lists

to_dict_of_lists(G[, nodelist])

Returns adjacency representation of graph as a dictionary of lists.

from_dict_of_lists(d[, create_using])

Returns a graph from a dictionary of lists.

to_edgelist(G[, nodelist])

Returns a list of edges in the graph.

from_edgelist(edgelist[, create_using])

Returns a graph from a list of edges.

Numpy

Functions to convert NetworkX graphs to and from numpy/scipy matrices.

The preferred way of converting data to a NetworkX graph is through the graph constructor. The constructor calls the to_networkx_graph() function which attempts to guess the input type and convert it automatically.

Examples

Create a 10 node random graph from a numpy matrix

>>> import numpy as np
>>> a = np.random.randint(0, 2, size=(10, 10))
>>> D = nx.DiGraph(a)

or equivalently

>>> D = nx.to_networkx_graph(a, create_using=nx.DiGraph)

See also

nx_agraph, nx_pydot

to_numpy_matrix(G[, nodelist, dtype, order, …])

Returns the graph adjacency matrix as a NumPy matrix.

to_numpy_array(G[, nodelist, dtype, order, …])

Returns the graph adjacency matrix as a NumPy array.

to_numpy_recarray(G[, nodelist, dtype, order])

Returns the graph adjacency matrix as a NumPy recarray.

from_numpy_matrix(A[, parallel_edges, …])

Returns a graph from numpy matrix.

from_numpy_array(A[, parallel_edges, …])

Returns a graph from NumPy array.

Scipy

to_scipy_sparse_matrix(G[, nodelist, dtype, …])

Returns the graph adjacency matrix as a SciPy sparse matrix.

from_scipy_sparse_matrix(A[, …])

Creates a new graph from an adjacency matrix given as a SciPy sparse matrix.

Pandas

to_pandas_adjacency(G[, nodelist, dtype, …])

Returns the graph adjacency matrix as a Pandas DataFrame.

from_pandas_adjacency(df[, create_using])

Returns a graph from Pandas DataFrame.

to_pandas_edgelist(G[, source, target, …])

Returns the graph edge list as a Pandas DataFrame.

from_pandas_edgelist(df[, source, target, …])

Returns a graph from Pandas DataFrame containing an edge list.