【问题标题】:How to transform a SciPy sparse matrix to a dictionary如何将 SciPy 稀疏矩阵转换为字典
【发布时间】:2019-08-17 18:59:56
【问题描述】:

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

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

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

【问题讨论】:

    标签: python dictionary scipy sparse-matrix


    【解决方案1】:

    我认为您可以将矩阵转换为基于键的稀疏矩阵格式的字典(比较scipy's documentation),然后通过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()))
    

    打印出来

    {(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}

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 2023-04-10
      • 2015-12-09
      • 2014-12-21
      • 2020-12-07
      • 1970-01-01
      • 2020-11-26
      • 2018-12-10
      • 2011-12-16
      相关资源
      最近更新 更多