Markus
Markus

Reputation: 1285

Check if scipy sparse matrix entry exists

I initialize an empty sparse matrix using

S = scipy.sparse.lil_matrix((n,n),dtype=int)

As expected print S doesn't show anything, since nothing has been assigned. Yet if I test:

print S[0,0]==0

I receive true.

Is there a way to test if a value has been set before? E.g. along the lines of ifempty?

Upvotes: 3

Views: 2917

Answers (1)

alko
alko

Reputation: 48347

You can check for stored values with

def get_items(s):
    s_coo = s.tocoo()
    return set(zip(s_coo.row, s_coo.col))

Demo:

>>> n = 100
>>> s = scipy.sparse.lil_matrix((n,n),dtype=int)
>>> s[10, 12] = 1
>>> (10, 12) in get_items(s)
True

Note that for other types of sparse matrices, 0 can be expicetely set:

>>> s = scipy.sparse.csr_matrix((n,n),dtype=int)
>>> s[12, 14] = 0
>>> (12, 14) in get_items(s)
True

Upvotes: 1

Related Questions