python - 如何将 scipy csr_matrix 转换回行、列和数据列表?

标签 python scipy sparse-matrix

我有一个按照文档中指定的方式创建的 scipy csr_matrix:

import numpy as np
from scipy.sparse import csr_matrix
row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])
mtr = csr_matrix((data, (row, col)))
mtr.toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])

我如何有效地将这样的矩阵 mtr 转换回最初的三个列表 rowcoldata?

最佳答案

正如您在评论中指出的那样,您可以通过访问 data 属性来获取数据。要获取行和列,您可以将数组转换为 COO 格式,并访问 datarowcol 属性:

这是你的数组mtr:

In [11]: mtr
Out[11]: 
<3x3 sparse matrix of type '<class 'numpy.int64'>'
    with 6 stored elements in Compressed Sparse Row format>

In [12]: mtr.A
Out[12]: 
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]], dtype=int64)

转换为 COO 格式,并访问 datarowcol 属性。

In [13]: c = mtr.tocoo()

In [14]: c.data
Out[14]: array([1, 2, 3, 4, 5, 6], dtype=int64)

In [15]: c.row
Out[15]: array([0, 0, 1, 2, 2, 2], dtype=int32)

In [16]: c.col
Out[16]: array([0, 2, 2, 0, 1, 2], dtype=int32)

关于python - 如何将 scipy csr_matrix 转换回行、列和数据列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47085975/

相关文章:

python - 子进程 Popen/call/check_output 之间的区别

python - 试图在 Instagram API 中查找关注者数量

python - 计算两个 Pandas 数据帧的行之间的欧几里得距离

numpy - scipy.linalg.eig 是否给出了正确的左特征向量?

python - 将对数正态分布的拟合 PDF 缩放为 python 中的直方图

python - 删除特定 csv 文件中的前导 0

python - 如何使用 Flask 显示 html 然后重定向到下载

multithreading - 使用 MKL BLAS 时,scipy 是否支持稀疏矩阵乘法的多线程?

python - 如何在Python上增量创建稀疏矩阵?

python - 具有稀疏数据的 tensorflow 训练