- 在 Numpy 中将(行、列、值)三元组数组转换为矩阵的最简单方法是什么?
- 如果我有任意数量的索引怎么办?
- 另外,将矩阵转换回(行、列、值)三元组的最简单方法是什么?
以下适用于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]])