在 csc_matrix 中查找零元素的行索引
Finding the row indices of zero elements in csc_matrix
我有一个 csc_matrix 这样的:
>>> arr_csc = arr.tocsc()
>>> arr_csc
<2x3 sparse matrix of type '<type 'numpy.int64'>'
with 5 stored elements in Compressed Sparse Column format>
>>> arr_csc.todense()
matrix([[0, 1, 0],
[3, 4, 0]])
现在,我想要的是每列中所有零元素的行索引。例如:
For column 0, I want "[0]"
For column 1, I want "[]"
For column 2. I want "[0, 1]"
最快的方法是什么?
谢谢!
这样的事情怎么样:
主要思想是使用 .indptr
和 .indices
,我的解决方案的其余部分可能可以改进。
from scipy import sparse
import numpy as np
arr_csc = sparse.csc_matrix([[0, 1, 0],
[3, 4, 0]])
result = []
all_rows = np.arange(arr_csc.shape[0])
for i in xrange(len(arr_csc.indptr) - 1):
start = arr_csc.indptr[i]
end = arr_csc.indptr[i+1]
result.append(np.setdiff1d(all_rows, arr_csc.indices[start : end]))
print result
结果:
[array([0]), array([], dtype=int64), array([0, 1])]
对于您的样本,这有效:
In [808]: arr=sparse.csc_matrix([[0,1,0],[3,4,0]])\
In [809]: arr1=arr==0
In [810]: arr1.T.tolil().rows
Out[810]: array([[0], [], [0, 1]], dtype=object)
请注意,当您执行 arr==0
时,您会收到警告:
/usr/lib/python3/dist-packages/scipy/sparse/compressed.py:220: SparseEfficiencyWarning: Comparing a sparse matrix with 0 using == is inefficient, try using != instead.
", try using != instead.", SparseEfficiencyWarning)
在您的示例中,0 和非零的数量相等。但是在一个典型的稀疏矩阵中,有更多的 0。许多 0 表示行列表很长。
我有一个 csc_matrix 这样的:
>>> arr_csc = arr.tocsc()
>>> arr_csc
<2x3 sparse matrix of type '<type 'numpy.int64'>'
with 5 stored elements in Compressed Sparse Column format>
>>> arr_csc.todense()
matrix([[0, 1, 0],
[3, 4, 0]])
现在,我想要的是每列中所有零元素的行索引。例如:
For column 0, I want "[0]"
For column 1, I want "[]"
For column 2. I want "[0, 1]"
最快的方法是什么?
谢谢!
这样的事情怎么样:
主要思想是使用 .indptr
和 .indices
,我的解决方案的其余部分可能可以改进。
from scipy import sparse
import numpy as np
arr_csc = sparse.csc_matrix([[0, 1, 0],
[3, 4, 0]])
result = []
all_rows = np.arange(arr_csc.shape[0])
for i in xrange(len(arr_csc.indptr) - 1):
start = arr_csc.indptr[i]
end = arr_csc.indptr[i+1]
result.append(np.setdiff1d(all_rows, arr_csc.indices[start : end]))
print result
结果:
[array([0]), array([], dtype=int64), array([0, 1])]
对于您的样本,这有效:
In [808]: arr=sparse.csc_matrix([[0,1,0],[3,4,0]])\
In [809]: arr1=arr==0
In [810]: arr1.T.tolil().rows
Out[810]: array([[0], [], [0, 1]], dtype=object)
请注意,当您执行 arr==0
时,您会收到警告:
/usr/lib/python3/dist-packages/scipy/sparse/compressed.py:220: SparseEfficiencyWarning: Comparing a sparse matrix with 0 using == is inefficient, try using != instead. ", try using != instead.", SparseEfficiencyWarning)
在您的示例中,0 和非零的数量相等。但是在一个典型的稀疏矩阵中,有更多的 0。许多 0 表示行列表很长。