Curriculum
Course: SCIPY
Login
Text lesson

Sparse Matrix Methods

Access the stored non-zero elements of a sparse matrix using the data property.

Example

import numpy as np
from scipy.sparse import csr_matrix

arr = np.array([[000], [001], [102]])

print(csr_matrix(arr).data)

Count the number of non-zero elements using the count_nonzero() method.

Example

import numpy as np
from scipy.sparse import csr_matrix

arr = np.array([[000], [001], [102]])

print(csr_matrix(arr).count_nonzero())

Remove zero entries from the matrix using the eliminate_zeros() method.

Example

import numpy as np
from scipy.sparse import csr_matrix

arr = np.array([[000], [001], [102]])

mat = csr_matrix(arr)
mat.eliminate_zeros()

print(mat)

Eliminate duplicate entries from the matrix using the sum_duplicates() method.

Example

Eliminate duplicates by summing them together.

import numpy as np
from scipy.sparse import csr_matrix

arr = np.array([[000], [001], [102]])

mat = csr_matrix(arr)
mat.sum_duplicates()

print(mat)

Convert from CSR to CSC format using the tocsc() method.

Example

import numpy as np
from scipy.sparse import csr_matrix

arr = np.array([[000], [001], [102]])

newarr = csr_matrix(arr).tocsc()

print(newarr)

Note: In addition to the sparse-specific operations, sparse matrices support all the operations that regular matrices do, such as reshaping, summing, arithmetic, broadcasting, and more.