SciPy Sparse Matrix
A sparse matrix refers to a matrix in numerical analysis in which the vast majority of values are zero. Conversely, if most elements are non-zero, the matrix is dense.
Large sparse matrices often appear when solving linear models in science and engineering.

In the figure above, the left side is a sparse matrix, which can be seen to contain many 0 elements, and the right side is a dense matrix, where most elements are non-zero.
Look at a simple example:
The above sparse matrix contains only 9 non-zero elements, and also contains 26 zero elements. Its sparsity is 74%, and its density is 26%.
SciPy'sscipy.sparsemodule provides functions for handling sparse matrices.
We mainly use the following two types of sparse matrices:
- CSC - Compressed Sparse Column, compressed by column.
- CSR - Compressed Sparse Row, compressed by row.
In this chapter, we mainly use the CSR matrix.
CSR Matrix
We can pass toscipy.sparse.csr_matrix()function an array to create a CSR matrix.
Example
Create a CSR matrix.
from scipy.sparse import csr_matrix
arr = np.array([0, 0, 0, 0, 0, 1, 1, 0, 2])
print(csr_matrix(arr))
The above code outputs the following result:
(0, 5) 1 (0, 6) 1 (0, 8) 2
Result analysis:
- First line: at the sixth position (index value 5) in the first row (index value 0) of the matrix, there is a value 1.
- Second line: at the seventh position (index value 6) in the first row (index value 0) of the matrix, there is a value 1.
- Third line: at the ninth position (index value 8) in the first row (index value 0) of the matrix, there is a value 2.
CSR Matrix Methods
We can usedataproperty to view the stored data (excluding 0 elements):
Example
from scipy.sparse import csr_matrix
arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]])
print(csr_matrix(arr).data)
The above code outputs the following result:
[1 1 2]
Usecount_nonzero()method to calculate the total number of non-zero elements:
Example
from scipy.sparse import csr_matrix
arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]])
print(csr_matrix(arr).count_nonzero())
The above code outputs the following result:
3
Useeliminate_zeros()method to remove 0 elements from the matrix:
Example
from scipy.sparse import csr_matrix
arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]])
mat = csr_matrix(arr)
mat.eliminate_zeros()
print(mat)
The above code outputs the following result:
(1, 2) 1 (2, 0) 1 (2, 2) 2
Use the sum_duplicates() method to remove duplicates:
Example
from scipy.sparse import csr_matrix
arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]])
mat = csr_matrix(arr)
mat.sum_duplicates()
print(mat)
The above code outputs the following result:
(1, 2) 1 (2, 0) 1 (2, 2) 2
Convert CSR to CSC using the tocsc() method:
Example
from scipy.sparse import csr_matrix
arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]])
newarr = csr_matrix(arr).tocsc()
print(newarr)
(2, 0) 1 (1, 2) 1 (2, 2) 2Other extensions