Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
695 views
in Technique[技术] by (71.8m points)

matrix - How to effectively combine disconnected csr matrices in python?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...