[英]Add column to a sparse matrix
When I execute the following code I get a spares matrix: 当我执行以下代码时,我得到一个备用矩阵:
import numpy as np
from scipy.sparse import csr_matrix
row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
sp = csr_matrix((data, (row, col)), shape=(3, 3))
print(sp)
(0, 0) 1
(0, 2) 2
(1, 2) 3
(2, 0) 4
(2, 1) 5
(2, 2) 6
I want to add another column to this sparse matrix so the output is: 我想在这个稀疏矩阵中添加另一列,因此输出为:
(0, 0) 1
(0, 2) 2
(0, 3) 7
(1, 2) 3
(1, 3) 7
(2, 0) 4
(2, 1) 5
(2, 2) 6
(2, 3) 6
Basically I want to add another column that has the values 7,7,7. 基本上我想添加另一个值为7,7,7的列。
The sparse.hstack
used in @Paul Panzer's
link is the simplest. 该
sparse.hstack
中使用@Paul Panzer's
链接是最简单的。
In [760]: sparse.hstack((sp,np.array([7,7,7])[:,None])).A
Out[760]:
array([[1, 0, 2, 7],
[0, 0, 3, 7],
[4, 5, 6, 7]], dtype=int32)
sparse.hstack
is not complicated; sparse.hstack
并不复杂; it just calls bmat([blocks])
. 它只是调用
bmat([blocks])
。
sparse.bmat
gets the coo
attributes of all the blocks, joins them with the appropriate offself, and builds a new coo_matrix
. sparse.bmat
获取所有块的coo
属性,将它们与适当的自身连接起来,并构建一个新的coo_matrix
。
In this case it joins 在这种情况下,它加入
In [771]: print(sp)
(0, 0) 1
(0, 2) 2
(1, 2) 3
(2, 0) 4
(2, 1) 5
(2, 2) 6
In [772]: print(sparse.coo_matrix(np.array([7,7,7])[:,None]))
(0, 0) 7
(1, 0) 7
(2, 0) 7
while changing the column numbers of the last to 3
. 同时将最后一列的列号更改为
3
。
In [761]: print(sparse.hstack((sp,np.array([7,7,7])[:,None])))
(0, 0) 1
(0, 2) 2
(1, 2) 3
(2, 0) 4
(2, 1) 5
(2, 2) 6
(0, 3) 7
(1, 3) 7
(2, 3) 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.