[英]Numpy: Transform sparse matrix to ndarray
I really couldn't google it. 我真的不能谷歌吧。 How to transform sparse matrix to ndarray? 如何将稀疏矩阵转换为ndarray?
Assume, I have sparse matrix t of zeros. 假设我有零稀疏矩阵t。 Then 然后
g = t.todense()
g[:10]
matrix([[0],
[0],
[0],
[0],
[0],
[0],
[0],
[0],
[0],
[0]])
instead of [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 代替[0,0,0,0,0,0,0,0,0,0]
Solution: 解:
t.toarray().flatten() t.toarray()。弄平()
Use np.asarray
: 使用np.asarray
:
>>> a = np.asarray(g)
>>> a
array([[0],
[0],
[0],
[0],
[0],
[0],
[0],
[0],
[0],
[0]])
Where g
is your dense matrix in the example (after calling t.todense()
). 其中g
是示例中的密集矩阵(在调用t.todense()
)。
You specifically asked for the output of 你特意要求输出
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
which has only one dimension. 它只有一个维度。 To get that, you'll want to flatten
the array: 为此,您需要flatten
数组:
>>> flat_array = np.asarray(g).flatten()
>>> flat_array
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Edit: 编辑:
You can skip straight to the array from the sparse matrix with: 您可以从稀疏矩阵直接跳到数组:
a = t.toarray()
转置矩阵以将第一列转换为第一列
g = g.T
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.