Mat*_*ien 5 python numpy scipy sparse-matrix
我有一个 numpy 数组,X:
type(X)
>>> <class 'scipy.sparse.csc.csc_matrix'>
Run Code Online (Sandbox Code Playgroud)
我有兴趣在第 0 列中找到具有非零条目的行的索引。我试过:
getcol = X.getcol(0)
print getcol
Run Code Online (Sandbox Code Playgroud)
这给了我:
(0, 0) 1
(2, 0) 1
(5, 0) 10
Run Code Online (Sandbox Code Playgroud)
这很棒,但我想要的是一个包含其中的向量0, 2, 5。
我如何获得我正在寻找的索引?
谢谢您的帮助。
使用 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])
Run Code Online (Sandbox Code Playgroud)
所以aa.indices[aa.indptr[col]:aa.indptr[col+1]]应该得到你想要的东西。