1

I have a sparce matrix (coo_matrix) like this:

type(matrix)
scipy.sparse.coo.coo_matrix

print(matrix)
  (0, 14)   1.0
  (1, 17)   1.0
  (3, 6)    1.0
  (6, 3)    1.0
  (12, 15)  2.0
  (12, 13)  3.0
  (13, 16)  2.0
  (13, 12)  3.0
  (14, 0)   1.0
  (15, 16)  1.0
  (15, 12)  2.0
  (16, 15)  1.0
  (16, 13)  2.0
  (17, 1)   1.0
  (18, 19)  1.0
  (19, 18)  1.0

I can sum this matrix, but the result is printed without row names, so it is unclear to which element this sum is belong:

print(matrix.sum(axis = 1))
[[1.]
 [1.]
 [0.]
 [1.]
 [0.]
 [0.]
 [1.]
 [0.]
 [0.]
 [0.]
 [0.]
 [0.]
 [5.]
 [5.]
 [1.]
 [3.]
 [3.]
 [1.]
 [1.]
 [1.]]

Is it possible to set the row names for matrix to print result like this (so the row name will be corresponding to the sparce matrix element):

0: 1
1: 1
3: 1
6: 1
12: 5
13: 5
14: 1
15: 3
16: 3
17: 1
18: 1
19: 1

I find a solution like this:

Mc=matrix.tocoo()
Mc_sum = {k:v for k,v in zip(Mc.col, Mc.sum(axis = 1))}

It gives almost desired output, but still not the one I want:

{17: matrix([[63.]]), 11: matrix([[25.]]), 5: matrix([[105.]]), 20: matrix([[31.]])...}
aynber
  • 22,380
  • 8
  • 50
  • 63
Vlad Fedo
  • 61
  • 5

1 Answers1

0

I found the matrix.row and matrix.col attributes helpful. Not too sure how dynamic you want this to be but the following gave me the desired output.

sums_to_list=sum(matrix.sum(axis = 1).tolist(), [])

for i, j in zip(matrix.row, sums_to_list):
    print(f'{i}: {j}')

The sums_to_list variable in the zip function unpacks a list of lists from the sum matrix provided and then turns it into a single list.

  • I try to run it on Kernel, however, for some reason the execution of `sums_to_list=sum(M.sum(axis = 1).tolist(), [])` is not proceed (endless execution time). – Vlad Fedo Dec 28 '22 at 08:33
  • I guess at this point you’ll have to find a more efficient manner to turn the list of list that `matrix.sum(axis = 1)` provides into a single list. Something like [this](https://stackoverflow.com/questions/17485747/how-to-convert-a-nested-list-into-a-one-dimensional-list-in-python) might help. Hard part is dealing with `coo_matrix`. – ArcTeryxOverAlteryx Dec 28 '22 at 11:51