繁体   English   中英

scipy:如何获取每一行的所有非零值索引?

[英]scipy: how to get all non-zero value index for each row?

除了《 SciPy v0.11参考指南》,我找不到有关scipy.sparse索引的更多信息。

The lil_matrix class supports basic slicing and fancy indexing with a similar syntax to NumPy arrays.
我已经阅读了有关索引的numpy文档,但是我不清楚,例如,

 Asp = sparse.lil_matrix((3,3)) Asp.setdiag(zeros(3)) Asp[0, 1:3] = 10 print Asp.todense() 

1.为什么输出

  [[0. 10. 10.]\n  [0. 0. 0.]\n  [0. 0. 0.]] 

[0,1:3]是什么意思? 如果我用

 Asp[0, 1:2,3] = 10 

有一个错误:

  IndexError:无效的索引 
,我不知道原因。

2.什么是最快获取每一行所有非零值的方法?

对于第二个问题,请使用nonzero()方法。 我必须仔细研究源代码才能找到它,因为在任何参考文档中都找不到。

def nonzero(self):
    """nonzero indices

    Returns a tuple of arrays (row,col) containing the indices
    of the non-zero elements of the matrix.

    Examples
    --------
    >>> from scipy.sparse import csr_matrix
    >>> A = csr_matrix([[1,2,0],[0,0,3],[4,0,5]])
    >>> A.nonzero()
    (array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2]))

    """

[0,1:3]是什么意思?

这意味着:第0行,元素13 (不包括)。 由于Numpy和Scipy使用从零开始的索引,因此第0行是第一行,而1:3表示第一列和第二列。

Asp[0, 1:2,3]无效,因为您有三个索引0 1:23 矩阵只有两个轴。

这是所有标准的Numpy内容; 阅读有关该软件包的任何优秀教程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM