查找稀疏csc_matrix中非零条目的行索引
我有一个numpy数组,叫做X:
type(X)
>>> <class 'scipy.sparse.csc.csc_matrix'>
我想找到第0列中非零值所在行的索引。我试过这个:
getcol = X.getcol(0)
print getcol
结果是:
(0, 0) 1
(2, 0) 1
(5, 0) 10
这个结果很好,但我想要的是一个包含0, 2, 5
的向量。
我该怎么才能得到我想要的索引呢?
谢谢大家的帮助。
1 个回答
3
使用CSC矩阵,你可以做以下事情:
>>> import scipy.sparse as sps
>>> a = np.array([[1, 0, 0],
... [0, 1, 0],
... [1, 0, 1],
... [0, 0, 1],
... [0, 1, 0],
... [1, 0, 1]])
>>> aa = sps.csc_matrix(a)
>>> aa.indices[aa.indptr[0]:aa.indptr[1]]
array([0, 2, 5])
>>> aa.indices[aa.indptr[1]:aa.indptr[2]]
array([1, 4])
>>> aa.indices[aa.indptr[2]:aa.indptr[3]]
array([2, 3, 5])
所以 aa.indices[aa.indptr[col]:aa.indptr[col+1]]
这段代码可以帮你获取你想要的内容。