如何将scipy csr_matrix转换回row,col和data列表?

Ser*_*rov 5 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]])
Run Code Online (Sandbox Code Playgroud)

如何有效地将这样的矩阵mtr回到初始三个列表row,coldata

War*_*ser 5

正如您在评论中所述,您可以通过访问该data属性来获取数据.要获得的行和列,你可以在阵列COO格式转换,并访问data,rowcol属性:

这是你的数组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)
Run Code Online (Sandbox Code Playgroud)

转换为COO格式,并访问data,rowcol属性.

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)
Run Code Online (Sandbox Code Playgroud)


sas*_*cha 3

只需调用my_csr_matrix.nonzero()然后进行索引即可。

代码:

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)))

print(mtr.todense())

rows, cols = mtr.nonzero()
data = mtr[rows, cols]

print(rows, cols, data)
Run Code Online (Sandbox Code Playgroud)

输出:

[[1 0 2]
 [0 0 3]
 [4 5 6]]
[0 0 1 2 2 2] [0 2 2 0 1 2] [[1 2 3 4 5 6]]
Run Code Online (Sandbox Code Playgroud)