SciPy's fancy indexing for csr_matrices

I'm new to Python, so forgive me ahead of time if this is an elementary question, but I searched around and didn't find a satisfactory answer.

I am trying to do the following with NumPy and SciPy:

I,J = x[:,0], x[:1] # x is a two column array of (r,c) pairs V = ones(len(I)) G = sparse.coo_matrix((V,(I,J))) # G dimensions are 1032570x1032570 G = G + transpose(G) r,c = G.nonzero() G[r,c] = 1 ... NotImplementedError: Fancy indexing in assignment not supported for csr matrices 

Basically, I want all non-zero values ​​to be 1 after adding transpose, but I get indexing error messages.

Alternatively, if I could show that the matrix G is symmetric, adding transpose is not required.

Any understanding of any of these approaches would be greatly appreciated.

+4
source share
1 answer

In addition to doing something like G = G / G , you can work with G.data .

So in your case do:

 G.data = np.ones(G.nnz) 

or

 G.data[G.data != 0] = 1 

Will do what you want. This is more flexible since it allows you to create other types of filters (for example, G.data[G.data > 0.9] = 1 or G.data = np.random.random(G.nnz) )

The second option will set values ​​only if they have a nonzero value. During some calculations, you end up with null values ​​that are "dense" (that is, they are actually stored as a value in a sparse array). (You can remove them in place using G.eliminate_zeros() )

+6
source

All Articles