Check if scipy sparse matrix entry exists

删除回忆录丶 提交于 2019-12-14 02:14:29

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/20577372/check-if-scipy-sparse-matrix-entry-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!