Search code examples
pythonarraysnumpymatrixsparse-matrix

How to concatenate more sparse matrices into one in python


I have a problem in python where i would like to merge some sparse matrices into one. The sparse matrices are of csr_matrix type and have same amount of rows. When I use hstack to stack them together I obtain an array of matrices, but I would like to obtain a single matrix with the number of rows (which is the same for every matrix) and as the number of columns the sum of the columns number of every matrix. Thanks for support.


Solution

  • You can do this using scipy.sparse.hstack. For example:

    import numpy as np
    from scipy import sparse
    
    x = sparse.csr_matrix(np.random.randint(0, 2, size=(10, 10)))
    y = sparse.csr_matrix(np.random.randint(0, 2, size=(10, 10)))
    xy = sparse.hstack([x, y])
    
    print(xy.shape)
    # (10, 20)
    
    print(type(xy))
    # <class 'scipy.sparse.coo.coo_matrix'>