Eine Nullenspalte zu einer csr_matrix hinzufügen
Ich habe ein MxN-Sparsecsr_matrix
, und ich möchte ein paar Spalten mit nur Nullen rechts von der Matrix hinzufügen. Grundsätzlich sind die Arraysindptr
, indices
unddata
Bleib gleich, also möchte ich nur die Dimensionen der Matrix ändern. Dies scheint jedoch nicht implementiert zu sein.
>>> 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 das horizontale Stapeln 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)
Das ist, was ich irgendwann erreichen möchte. Gibt es eine schnelle Möglichkeit, mein @ umzugestaltecsr_matrix
ohne alles 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]])