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),
....]
2 个解决方案
#1
5
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]) )
#2
2
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. zip
can be used to transpose the output.
成员函数非零以切片可接受的格式返回所有非零的坐标,以便A [A.nonzero()]为您提供所有非零元素的平面数组。 zip可用于转置输出。
#1
5
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]) )
#2
2
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. zip
can be used to transpose the output.
成员函数非零以切片可接受的格式返回所有非零的坐标,以便A [A.nonzero()]为您提供所有非零元素的平面数组。 zip可用于转置输出。