Access the stored non-zero elements of a sparse matrix using the data
property.
import numpy as np arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]]) print(csr_matrix(arr).data) |
Count the number of non-zero elements using the count_nonzero()
method.
import numpy as np arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]]) print(csr_matrix(arr).count_nonzero()) |
Remove zero entries from the matrix using the eliminate_zeros() method.
import numpy as np arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]]) mat = csr_matrix(arr) print(mat) |
Eliminate duplicate entries from the matrix using the sum_duplicates()
method.
Eliminate duplicates by summing them together.
import numpy as np arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]]) mat = csr_matrix(arr) print(mat) |
Convert from CSR to CSC format using the tocsc() method.
import numpy as np arr = np.array([[0, 0, 0], [0, 0, 1], [1, 0, 2]]) 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.