2017-01-30 56 views
3

当我执行下面的代码,我收到了备用矩阵:添加列到稀疏矩阵

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 

我想另一列添加到该稀疏矩阵所以输出:

(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 

基本上我想添加另一个值为7,7,7的列。

+1

看看[这里](http://stackoverflow.com/questions/19710602/concatenate-sparse-matrices-in-python-using-scipy-numpy) –

回答

7

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并不复杂;它只是叫bmat([blocks])

sparse.bmat获取所有块的coo属性,并将它们加入适当的自身,然后构建新的coo_matrix

在这种情况下,它加入

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 

而改变最后的列号码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 
+0

谢谢大家了明确的解释。 – Bonson