Sparse Matrices

In this lesson, we will learn about different sparse matrices in Python and the conversion between sparse and dense matrices.

Sparse matrices in Python #

The procedure we have used so far to construct the matrix for a is not very efficient. A full matrix is created, which consists mostly of zeros with non-zero values only appearing on diagonals. There are more efficient routines that store what are called sparse matrices. In a sparse matrix, only the value and location of non-zero values in a matrix are stored. Functionality for sparse matrices is available in the scipy submodule sparse.

We will import the scipy.sparse submodule as sp.

import scipy.sparse as sp

Dense to sparse #

When we create a sparse matrix, we have to choose which format it should be stored in. There are many ways to store a sparse matrix. Two most commonly used are:

  1. compressed sparse column using the csc_matrix(A) method.
  2. compressed sparse row using the csr_matrix(A) method.

The following matrix is an example of this:

Get hands-on with 1400+ tech skills courses.