Graphs are a fundamental data structure, and SciPy offers the scipy.sparse.csgraph
module for efficiently working with them.
An adjacency matrix is an n×nn \times n matrix, where nn represents the number of elements in a graph, and the values indicate the connections between those elements.
Example:
For a graph with elements A, B, and C, the connections are as follows:
The adjacency matrix for this graph would be:
A B C A:[0 1 2] B:[1 0 0] C:[2 0 0] |
Here are some of the most commonly used methods for working with adjacency matrices.
Use the connected_components() method to identify all the connected components.
import numpy as np from scipy.sparse.csgraph import connected_components from scipy.sparse import csr_matrix arr = np.array([ [0, 1, 2], [1, 0, 0], [2, 0, 0] ]) newarr = csr_matrix(arr) print(connected_components(newarr)) |