Say I would like to remove the diagonal from scipy.sparse.csr_matrix. Is there an effective way to do this? I saw that the module sparsetoolshas functions Cto return the diagonal.
Based on other SO answers here and here, my current approach is this:
def csr_setdiag_val(csr, value=0):
"""Set all diagonal nonzero elements
(elements currently in the sparsity pattern)
to the given value. Useful to set to 0 mostly.
"""
if csr.format != "csr":
raise ValueError('Matrix given must be of CSR format.')
csr.sort_indices()
pointer = csr.indptr
indices = csr.indices
data = csr.data
for i in range(min(csr.shape)):
ind = indices[pointer[i]: pointer[i + 1]]
j = ind.searchsorted(i)
if j == len(ind):
continue
j += pointer[i]
if indices[j] == i:
data[j] = value
which I then follow with
csr.eliminate_zeros()
Is this the best I can do without writing my own Cythoncode?
source
share