2
  1. 在 Numpy 中将(行、列、值)三元组数组转换为矩阵的最简单方法是什么?
  2. 如果我有任意数量的索引怎么办?
  3. 另外,将矩阵转换回(行、列、值)三元组的最简单方法是什么?

以下适用于3,但感觉很迂回

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]])
4

1 回答 1

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]))
于 2012-12-06T16:31:43.410 回答