Scipy list of list with integers 中的稀疏矩阵

Scipy sparse matrix from list of list with integers

如何从包含整数(或字符串)的列表列表中生成 scipy 稀疏矩阵?

[[1,2,3],
 [1],
 [1,4,5]]

应该变成:

[[1, 1, 1, 0, 0],
 [1, 0, 0, 0, 0],
 [1, 0, 0, 1, 1]]

但是 scipy 的压缩稀疏格式呢?

我假设您想在末尾有一个 5 x 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]])