scipy - Accessing sparse matrix elements -


i have large sparse matrix of type 'scipy.sparse.coo.coo_matrix'. can convert csr .tocsr(), .todense() not work since array large. want able extract elements matrix regular array, may pass row elements function.

for reference, when printed, matrix looks follows:

(7, 0)  0.531519363001 (48, 24)    0.400946334437 (70, 6) 0.684460955022 ... 

make matrix 3 elements:

in [550]: m = sparse.coo_matrix(([.5,.4,.6],([0,1,2],[0,5,3])), shape=(5,7)) 

it's default display (repr(m)):

in [551]: m out[551]:  <5x7 sparse matrix of type '<class 'numpy.float64'>'     3 stored elements in coordinate format> 

and print display (str(m)) - looks input:

in [552]: print(m)   (0, 0)    0.5   (1, 5)    0.4   (2, 3)    0.6 

convert csr format:

in [553]: mc=m.tocsr() in [554]: mc[1,:]   # row 1 matrix (1 row): out[554]:  <1x7 sparse matrix of type '<class 'numpy.float64'>'     1 stored elements in compressed sparse row format>  in [555]: mc[1,:].a    # row 2d array out[555]: array([[ 0. ,  0. ,  0. ,  0. ,  0. ,  0.4,  0. ]])  in [556]: print(mc[1,:])    # 2nd element of m except row number   (0, 5)    0.4 

individual element:

in [560]: mc[1,5] out[560]: 0.40000000000000002 

the data attributes of these format (if want dig further)

in [562]: mc.data out[562]: array([ 0.5,  0.4,  0.6]) in [563]: mc.indices out[563]: array([0, 5, 3], dtype=int32) in [564]: mc.indptr out[564]: array([0, 1, 2, 3, 3, 3], dtype=int32) in [565]: m.data out[565]: array([ 0.5,  0.4,  0.6]) in [566]: m.col out[566]: array([0, 5, 3], dtype=int32) in [567]: m.row out[567]: array([0, 1, 2], dtype=int32) 

Comments