2017-01-30 162 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