将列表和列表的列表转换为scipy稀疏数组

12 投票
1 回答
10074 浏览
提问于 2025-04-18 14:33

假设我有一个列表,或者说是一个列表的列表(每个列表的大小都一样)。我该如何把它们转换成稀疏向量或稀疏矩阵呢?

1 个回答

15
In [5]: scipy.sparse.csr_matrix([[1, 2], [3, 0]])
Out[5]:
<2x2 sparse matrix of type '<type 'numpy.int64'>'
        with 3 stored elements in Compressed Sparse Row format>

In [6]: scipy.sparse.csr_matrix([1, 2])
Out[6]:
<1x2 sparse matrix of type '<type 'numpy.int64'>'
        with 2 stored elements in Compressed Sparse Row format>

你可以使用 scipy.sparse.whatever_matrix_type(your_data_structure) 这个命令来创建稀疏矩阵。这和你获取普通数组的方式很相似。需要注意的是,稀疏数据里没有稀疏向量或稀疏ndarray这种类,只有稀疏矩阵。

撰写回答