简体   繁体   English

将Scipy稀疏矩阵转换为元组

[英]Converting Scipy sparse matrix to tuple

I have a sparse matrix lets say A. 我有一个稀疏矩阵让我们说A.

where 哪里

type(A) 
scipy.sparse.csr.csr_matrix


and A 和A.

<100x100 sparse matrix of type '<class 'numpy.int64'>'
with 198 stored elements in Compressed Sparse Row format>

Following below is obtained 获得以下内容

(0, 1)  1
(0, 0)  1
(0, 2)  1
(0, 3)  1
(0, 4)  1
(0, 5)  1
(0, 6)  1
....

Which represents the non zero elements in the matrix A. (Code below) 它代表矩阵A中的非零元素。(下面的代码)

for a in A:
  print(a)

How do I convert this to a data structure like below: 如何将其转换为如下所示的数据结构:

[(0,1),
(0,0),
(0,2),
....]

You can try this kind of zip. 你可以试试这种拉链。 The main idea is to use the nonzero() method 主要思想是使用nonzero()方法

for i in range(len(A.nonzero()[0])):
     print( (A.nonzero()[0][i],A.nonzero()[1][i]) )

Assuming your question is "How do I get the coordinates of A's nonzero elements as a list" the following oneliner might be what you want: 假设您的问题是“如何将A的非零元素的坐标作为列表”,以下oneliner可能是您想要的:

zip(*A.nonzero())

The member function nonzero returns the coordinates of all nonzeros in a format acceptable for slicing so that A[A.nonzero()] gives you a flat array of all nonzero elements. 成员函数nonzero以切片可接受的格式返回所有nonzero的坐标,以便A[A.nonzero()]为您提供所有非零元素的平面数组。 zip can be used to transpose the output. zip可用于转置输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM