如何将 SciPy 稀疏矩阵转换为字典

Dor*_*old 5 python dictionary scipy sparse-matrix

我正在寻找一种将稀疏矩阵 ( scipy.sparse.csr.csr_matrix) 转换为 Python 字典的有效方法。

据我了解,稀疏矩阵在内部以类似于字典的形式保存数据,所以看起来这样的转换应该是微不足道的和快速的。

但是,我找不到任何可以做到这一点的方法。

jda*_*amp 4

我认为您可以将矩阵转换为基于键的稀疏矩阵格式的字典(比较scipy 的文档),然后通过以下items方法访问底层字典属性:

import numpy as np
from scipy.sparse import csr_matrix

c = csr_matrix(np.array([[1,2,3],
                         [4,5,6],
                         [7,8,9]])) # construct an example matrix
d = c.todok() # convert to dictionary of keys format
print(dict(d.items()))
Run Code Online (Sandbox Code Playgroud)

这打印出来

{(0, 0): 1, (1, 0): 4, (2, 0): 7, (0, 1): 2, (1, 1): 5, (2, 1): 8, ( 0, 2): 3, (1, 2): 6, (2, 2): 9}