以下适用于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]])
答案 0 :(得分: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]))