Scipy 无法在不复制数据的情况下执行此操作,但您可以通过更改定义稀疏矩阵的属性自行完成。
构成 csr_matrix 的属性有 4 个:
data:包含矩阵中实际值的数组
indices:一个数组,包含与data中每个值对应的列索引
indptr:一个数组,指定每行数据中第一个值之前的索引。如果该行为空,则索引与上一列相同。
shape:包含矩阵形状的元组
如果您只是在底部添加一行零,您只需更改矩阵的形状和 indptr。
x = np.ones((3,5))
x = csr_matrix(x)
x.toarray()
>> array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
# reshape is not implemented for csr_matrix but you can cheat and do it yourself.
x._shape = (4,5)
# Update indptr to let it know we added a row with nothing in it. So just append the last
# value in indptr to the end.
# note that you are still copying the indptr array
x.indptr = np.hstack((x.indptr,x.indptr[-1]))
x.toarray()
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 0., 0., 0., 0., 0.]])
这是一个处理更一般的 vstacking 任意 2 个 csr_matrices 情况的函数。您最终仍然会复制底层的 numpy 数组,但它仍然比 scipy vstack 方法快得多。
def csr_vappend(a,b):
""" Takes in 2 csr_matrices and appends the second one to the bottom of the first one.
Much faster than scipy.sparse.vstack but assumes the type to be csr and overwrites
the first matrix instead of copying it. The data, indices, and indptr still get copied."""
a.data = np.hstack((a.data,b.data))
a.indices = np.hstack((a.indices,b.indices))
a.indptr = np.hstack((a.indptr,(b.indptr + a.nnz)[1:]))
a._shape = (a.shape[0]+b.shape[0],b.shape[1])
return a