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 common data containers like numpy arrays, scipy sparse arrays, and pandas DataFrames.

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 array

>>> import numpy as np
>>> rng = np.random.default_rng()
>>> a = rng.integers(low=0, high=2, size=(10, 10))
>>> DG = nx.from_numpy_array(a, create_using=nx.DiGraph)

or equivalently:

>>> DG = nx.DiGraph(a)

which calls from_numpy_array internally based on the type of a.

See Also#

nx_agraph, nx_pydot

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

Returns the graph adjacency matrix as a NumPy array.

from_numpy_array(A[, parallel_edges, ...])

Returns a graph from a 2D NumPy array.

Scipy#

to_scipy_sparse_array(G[, nodelist, dtype, ...])

Returns the graph adjacency matrix as a SciPy sparse array.

from_scipy_sparse_array(A[, parallel_edges, ...])

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

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.