Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.where equivalent for csr_matrix python

I am trying to use numpy.where with csr_matrix, which dose not work. I am asking is there some built in function equivalent to numpy.where for sparse matrix. Here is an example of what I would like to do without using Forloop or .todense()

 import scipy.sparse as spa
 import numpy as np
 N = 100
 A = np.zeros((N,N))

 di = np.diag_indices((len(A[:,0])))
 A[di] = 2.3
 '''
 adding some values to non-diagonal terms 
 for sake of example 
 '''
 for k in range(0,len(A)-1):
     for j in range(-1,3,2):
         A[k,k+j] = 4.0
 A[2,3] =0.1
 A[3,3] = 0.1
 A[0,4] = 0.2
 A[0,2] = 3

 '''
 creating sparse matrix
 '''
 A = spa.csc_matrix((N,N))
 B = spa.csc_matrix((N,N))

 '''
 Here I get
 TypeError: unsupported operand type(s) for &: 'csc_matrix' and 'csc_matrix'
 '''

 ind1 = np.where((A>0.0) & (A<=1.0)) 
 B[ind1] = (3.0-B[ind1])**5-6.0*(2.0-B[ind1])**5
like image 764
madf19 Avatar asked Dec 31 '25 16:12

madf19


1 Answers

How about working with underlying arrays for A and B, the data arrays

In [36]: ind2=np.where((A.data>0.0)&(A.data<=1.0))

In [37]: A.indices[ind2]
Out[37]: array([2, 3, 0])

In [38]: A.indptr[ind2]
Out[38]: array([28, 31, 37])

In [39]: A.data[ind2]
Out[39]: array([ 0.1,  0.1,  0.2])

In [41]: B.data[ind2]=(3.0-B.data[ind2])**5-6.0*(2.0-B.data[ind2])**5

In [42]: B.data[ind2]
Out[42]: array([ 56.54555,  56.54555,  58.7296 ])

To see what ind2 corresponds to in the dense version, convert the array to coo

In [53]: Ac=A.tocoo()

In [54]: (Ac.row[ind2], Ac.col[ind2])
Out[54]: (array([2, 3, 0]), array([3, 3, 4]))

where, for reference, the where on the dense array is:

In [57]: np.where((A.A>0.0) & (A.A<=1.0))
Out[57]: (array([0, 2, 3]), array([4, 3, 3]))

One important caution - working with A.data means you exclude all of the zero entries of the dense array.

like image 98
hpaulj Avatar answered Jan 02 '26 06:01

hpaulj