Ich habe eine MxN Sparse csr_matrix
, und ich möchte ein paar Spalten mit nur Nullen auf der rechten Seite der Matrix hinzufügen. Im Prinzip bleiben die Arrays indptr
, indices
und data
gleich, daher möchte ich nur die Dimensionen der Matrix ändern. Dies scheint jedoch nicht implementiert zu sein.Hinzufügen einer Spalte von Nullen zu einer 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.
Auch horizontale Stapelung einer Nullmatrix scheint nicht zu funktionieren.
>>> 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)
Dies ist, was ich schließlich erreichen möchte. Gibt es einen schnellen Weg, um meine csr_matrix
umzuformen, ohne alles darin zu kopieren?
>>> 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]])