2012-12-06 31 views
2
  1. 在Numpy中將(行,列,值)三元組數組轉換爲矩陣的最簡單方法是什麼?
  2. 如果我有任意數量的指數,那麼如何?
  3. 此外,將矩陣轉換回(行,列,值)三元組最簡單的方法是什麼?

爲3以下的作品,但感覺很婉轉從NumPy中的(行,列,值)三元組中創建一個矩陣

In [1]: M = np.arange(9).reshape((3,3)) 

In [2]: M 
Out[2]: 
array([[0, 1, 2], 
     [3, 4, 5], 
     [6, 7, 8]]) 

In [3]: (rows, cols) = np.where(M) 

In [4]: vals = M[rows, cols] 

In [5]: zip(rows, cols, vals) 
Out[5]: 
[(0, 1, 1), 
(0, 2, 2), 
(1, 0, 3), 
(1, 1, 4), 
(1, 2, 5), 
(2, 0, 6), 
(2, 1, 7), 
(2, 2, 8)] 

而1以下的作品,但需要scipy.sparse

In [6]: import scipy.sparse as sp 

In [7]: sp.coo_matrix((vals, (rows, cols))).todense() 
Out[7]: 
matrix([[0, 1, 2], 
     [3, 4, 5], 
     [6, 7, 8]]) 

回答

2

就像這樣:

a=empty([max(rows)+1, max(cols)+1]) 
a[rows,cols] = vals 
array([[ 3.71697611e-307, 1.00000000e+000, 2.00000000e+000], 
    [ 3.00000000e+000, 4.00000000e+000, 5.00000000e+000], 
    [ 6.00000000e+000, 7.00000000e+000, 8.00000000e+000]]) 

請注意,您沒有(0,0)的值在您的名單,因此奇怪的價值。 應該適用於任何數量的值。 找回指數:

unravel_index(range(9), a.shape) 
(array([0, 0, 0, 1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2, 0, 1, 2])) 
+1

我的猜測是在任何欠缺位置的值應爲0更改'empty'爲'zeros'使你的代碼工作的方式。 –