Search code examples
pythonscipysparse-matrixis-empty

How to check if a SciPy CSR matrix is empty (i.e. contains only zeroes)?


What is the canonical way to check if a SciPy CSR matrix is empty (i.e. contains only zeroes)?

I use nonzero():

def is_csr_matrix_only_zeroes(my_csr_matrix):
    return(len(my_csr_matrix.nonzero()[0]) == 0)

from scipy.sparse import csr_matrix
print(is_csr_matrix_only_zeroes(csr_matrix([[1,2,0],[0,0,3],[4,0,5]])))
print(is_csr_matrix_only_zeroes(csr_matrix([[0,0,0],[0,0,0],[0,0,0]])))
print(is_csr_matrix_only_zeroes(csr_matrix((2,3))))
print(is_csr_matrix_only_zeroes(csr_matrix([[0,0,0],[0,1,0],[0,0,0]])))

outputs

False
True
True
False

but I wonder whether there exist more direct or efficient ways.

(Related but different: Check if scipy sparse matrix entry exists)


Solution

  • my_csr_matrix.nnz == 0
    

    The nnz attribute records the Number of NonZero entries... unless your CSR matrix is in a weird, nonnormalized form, for example if it has duplicate entries or explicitly stored zeros.

    If you have to deal with duplicate entries or explicit zeros, you can use the much more expensive csr_matrix.count_nonzero method:

    my_csr_matrix.count_nonzero() == 0