Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two scipy sparse matrices matrix_1 and matrix_2. Their dimensions are as follows:

<628x628 sparse matrix of type '<class 'numpy.float64'>'
<411x411 sparse matrix of type '<class 'numpy.float64'>'

I am trying to combine these two matrices in a way that two disconnected matrices will be in a single csr matrix.

For examle, let's say two matrices are

  1 2 3      1 2 3
1 0 0 1    1 1 1 0
2 1 0 1    2 1 1 1
3 1 1 0    3 0 1 0

and after the operation, the result should be

  1 2 3 4 5 6          1 2 3 4 5 6
1 0 0 1              1 0 0 1 0 0 0
2 1 0 1              2 1 0 1 0 0 0
3 1 1 0           => 3 1 1 0 0 0 0
4       1 1 0        4 0 0 0 1 1 0
5       1 1 1        5 0 0 0 1 1 1
6       0 1 0        6 0 0 0 0 1 0

I have checked the documentation of the scipy, and found vstack and hstack functions, but they did not work since the dimensions of the matrices are not the same. Even though the dimensions hold, they wouldn't give the result I want since these two graphs are disconnected.

I have checked these stackoverflow questions:

scipy append all rows of one sparse matrix to another How to concatenate two matrices in Python?

and many more unrelated posts but I couldn't come up with an effective solution. The only idea I have found is to convert csr matrices to dictionaries, append them and convert it to a csr matrix back but it seems highly inefficient. Is there an efficient way to do this with scipy and python?

Thank you for your assistance in advance!

question from:https://stackoverflow.com/questions/65897116/how-to-effectively-combine-disconnected-csr-matrices-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
709 views
Welcome To Ask or Share your Answers For Others

1 Answer

As hpaulj suggested in the comments,

import scipy.sparse as sp
combined_matrix = sp.bmat([[graph_1, None], [None, graph_2]], format="csr")

solved my problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...