adjacency_matrix#

adjacency_matrix(G, nodelist=None, dtype=None, weight='weight')[source]#

Returns adjacency matrix of G.

Parameters:
Ggraph

A NetworkX graph

nodelistlist, optional

The rows and columns are ordered according to the nodes in nodelist. If nodelist=None (the default), then the ordering is produced by G.nodes().

dtypeNumPy data-type, optional

The desired data-type for the array. If None, then the NumPy default is used.

weightstring or None, optional (default=’weight’)

The edge data key used to provide each value in the matrix. If None, then each edge has weight 1.

Returns:
ASciPy sparse array

Adjacency matrix representation of G.

See also

to_numpy_array
to_scipy_sparse_array
to_dict_of_dicts
adjacency_spectrum

Notes

For directed graphs, entry i, j corresponds to an edge from i to j.

If you want a pure Python adjacency matrix representation try to_dict_of_dicts() which will return a dictionary-of-dictionaries format that can be addressed as a sparse matrix.

For multigraphs with parallel edges the weights are summed. See networkx.convert_matrix.to_numpy_array() for other options.

The convention used for self-loop edges in graphs is to assign the diagonal matrix entry value to the edge weight attribute (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge weight is desired the resulting SciPy sparse array can be modified as follows:

>>> G = nx.Graph([(1, 1)])
>>> A = nx.adjacency_matrix(G)
>>> A.toarray()
array([[1]])
>>> A.setdiag(A.diagonal() * 2)
>>> A.toarray()
array([[2]])

Additional backends implement this function

graphblas : OpenMP-enabled sparse linear algebra backend.