gpt4 book ai didi

python - 查找稀疏 csc_matrix 中存在非零条目的行的索引

转载 作者:太空宇宙 更新时间:2023-11-03 11:04:42 28 4
gpt4 key购买 nike

我有一个 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 的向量。

如何获得我正在寻找的索引?

感谢您的帮助。

最佳答案

使用 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]] 应该可以满足您的需求。

关于python - 查找稀疏 csc_matrix 中存在非零条目的行的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23054680/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com