Adding a column of zeroes to a csr_matrix

前端 未结 2 805
一整个雨季
一整个雨季 2021-01-05 07:01

I have an MxN sparse csr_matrix, and I\'d like to add a few columns with only zeroes to the right of the matrix. In principle, the arrays indptr, <

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-05 07:45

    You can use scipy.sparse.vstack or scipy.sparse.hstack to do it faster:

    from scipy.sparse import csr_matrix, vstack, hstack
    
    B = csr_matrix((5, 2), dtype=int)
    C = csr_matrix((5, 2), dtype=int)
    D = csr_matrix((10, 10), dtype=int)
    
    B2 = vstack((B, C))
    #<10x2 sparse matrix of type ''
    #        with 0 stored elements in COOrdinate format>
    
    hstack((B2, D))
    #<10x12 sparse matrix of type ''
    #        with 0 stored elements in COOrdinate format>
    

    Note that the output is a coo_matrix, which can be efficiently converted to the CSR or CSC formats.

提交回复
热议问题