Shweta
Shweta

Reputation: 1161

python - how to check if matrix is sparse or not

I have a matrix and I want to check if it is sparse or not.

Things I have tried:

  1. isinstance method:

    if isinstance(<matrix>, scipy.sparse.csc.csc_matrix):
    

This works fine if I know exactly which sparse class I want to check.

  1. getformat method: But it assumes that my matrix is sparse and give format

But I want a way to know if matrix is sparse or not, and should work irrespective of which sparse class.

Kindly help me.

Upvotes: 28

Views: 17073

Answers (2)

Mai N.
Mai N.

Reputation: 33

You can do sparsity = 1.0 - count_nonzero(X) / X.size

This works for any matrices.

Upvotes: 2

Boa
Boa

Reputation: 2677

scipy.sparse.issparse(my_matrix)

Upvotes: 45

Related Questions