如何从包含整数(或字符串)的列表列表中创建一个scipy稀疏矩阵?
[[1,2,3],
[1],
[1,4,5]]
应该成为:
[[1, 1, 1, 0, 0],
[1, 0, 0, 0, 0],
[1, 0, 0, 1, 1]]
然后用scipy的压缩稀疏格式?
答案 0 :(得分:2)
我假设您希望最后有一个5乘5的矩阵。指数也从0开始。
In [18]:import scipy.sparse as sp
In [20]: a = [[0,1,2],[0],[0,3,4]]
In [31]: m = sp.lil_matrix((5,5), dtype=int)
In [32]: for row_index, col_indices in enumerate(a):
m[row_index, col_indices] = 1
....:
In [33]: m.toarray()
Out[33]:
array([[1, 1, 1, 0, 0],
[1, 0, 0, 0, 0],
[1, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])