python - Adding a column of zeroes to a csr_matrix -
python - Adding a column of zeroes to a csr_matrix -
i have mxn sparse csr_matrix
, , i'd add together few columns zeroes right of matrix. in principle, arrays indptr
, indices
, data
maintain same, want alter dimensions of matrix. however, seems not implemented.
>>> = csr_matrix(np.identity(5), dtype = int) >>> a.toarray() array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]) >>> a.shape (5, 5) >>> a.shape = ((5,7)) notimplementederror: reshaping not implemented csr_matrix.
also horizontally stacking 0 matrix not seem work.
>>> b = csr_matrix(np.zeros([5,2]), dtype = int) >>> b.toarray() array([[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]) >>> np.hstack((a,b)) array([ <5x5 sparse matrix of type '<type 'numpy.int32'>' 5 stored elements in compressed sparse row format>, <5x2 sparse matrix of type '<type 'numpy.int32'>' 0 stored elements in compressed sparse row format>], dtype=object)
this want accomplish eventually. there quick way reshape csr_matrix
without copying in it?
>>> c = csr_matrix(np.hstack((a.toarray(), b.toarray()))) >>> c.toarray() array([[1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0]])
what want isn't numpy or scipy understand reshape. particular case, can create new csr matrix reusing data
, indices
, indptr
original one, without copying them:
import scipy.sparse sps = sps.rand(10000, 10000, density=0.01, format='csr') in [19]: %timeit sps.csr_matrix((a.data, a.indices, a.indptr), ... shape=(10000, 10020), copy=true) 100 loops, best of 3: 6.26 ms per loop in [20]: %timeit sps.csr_matrix((a.data, a.indices, a.indptr), ... shape=(10000, 10020), copy=false) 10000 loops, best of 3: 47.3 per loop in [21]: %timeit sps.csr_matrix((a.data, a.indices, a.indptr), ... shape=(10000, 10020)) 10000 loops, best of 3: 48.2 per loop
so if no longer need original matrix a
, since default copy=false
, do:
a = sps.csr_matrix((a.data, a.indices, a.indptr), shape=(10000, 10020))
python numpy scipy sparse-matrix
Comments
Post a Comment