我有一个MxN稀疏csr_matrix
,我想在矩阵的右侧添加只有零的几列。原则上,阵列indptr
,indices
和data
保持不变,所以我只想改变矩阵的尺寸。但是,这似乎没有实施。将一列零添加到csr_matrix中
>>> A = 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 for csr_matrix.
也水平堆叠零矩阵似乎没有工作。
>>> 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'>'
with 5 stored elements in Compressed Sparse Row format>,
<5x2 sparse matrix of type '<type 'numpy.int32'>'
with 0 stored elements in Compressed Sparse Row format>], dtype=object)
这是我最终想达到的。有没有一种快速的方法来重塑我的csr_matrix
而不复制所有内容?
>>> 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]])