+1 vote
in Programming Languages by (14.2k points)
In a CSR matrix, some values are >1 and some are <-1. I want to set all such values to 1. Is there any function to set all non-zero values to 1 in a CSR matrix?

1 Answer

+3 votes
by (86.3k points)
selected by
 
Best answer

Setting all non-zero values to 1 in a CSR matrix is very simple. You do not need any function for it. The 'data' attribute of csr_matrix returns all non_zero values of the matrix; you can use the 'data' attribute to set them to 1.

Here is an example:

>>> import numpy as np

>>> from scipy.sparse import csr_matrix

>>> a= np.array([[0,0,2], [-1,0,1], [-2,0,0], [1,0,-1]])

>>> X_all = csr_matrix(a)

>>> X_all.data

array([ 2, -1,  1, -2,  1, -1])

>>> X_all.data[:] = 1

>>> X_all.data

array([1, 1, 1, 1, 1, 1])


...