Curriculum
Course: SCIPY
Login
Text lesson

SciPy Graph

Working with Graphs

Graphs are a fundamental data structure, and SciPy offers the scipy.sparse.csgraph module for efficiently working with them.

Adjacency Matrix

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:

scipy_graph

For a graph with elements A, B, and C, the connections are as follows:

  • A and B are connected with a weight of 1.
  • A and C are connected with a weight of 2.
  • C and B are not connected.

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.

Connected Components

Use the connected_components() method to identify all the connected components.

Example

import numpy as np
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix

arr = np.array([
  [012],
  [100],
  [200]
])

newarr = csr_matrix(arr)

print(connected_components(newarr))