python - Find first nonzero column in scipy.sparse matrix -
i looking first column containing nonzero element in sparse matrix (scipy.sparse.csc_matrix). actually, first column starting i-th 1 contain nonzero element.
this part of type of linear equation solver. dense matrices had following: (relevant line pcol = ...)
import numpy d = numpy.matrix([[1,0,0],[2,0,0],[3,0,1]]) = 1 pcol = + numpy.argmax(numpy.any(d[:,i:], axis=0)) if pcol != i: # pivot columns i, pcol d[:,[i,pcol]] = d[:,[pcol,i]] print(d) # result should numpy.matrix([[1,0,0],[2,0,0],[3,1,0]]) the above should swap columns 1 , 2. if set i = 0 instead, d unchanged since column 0 contains nonzero entries.
what efficient way scipy.sparse matrices? there analogues numpy.any() , numpy.argmax() functions?
with csc matrix easy find nonzero columns.
in [302]: arr=sparse.csc_matrix([[0,0,1,2],[0,0,0,2]]) in [303]: arr.a out[303]: array([[0, 0, 1, 2], [0, 0, 0, 2]]) in [304]: arr.indptr out[304]: array([0, 0, 0, 1, 3]) in [305]: np.diff(arr.indptr) out[305]: array([0, 0, 1, 2]) the last line shows how many nonzero terms there in each column.
np.nonzero(np.diff(arr.indptr))[0][0] index of first nonzero value in diff.
do same on csr matrix find 1st nonzero row.
i can elaborate on indptr if want.
Comments
Post a Comment