Skip to main content
 首页 » 编程设计

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

2025年05月04日18shihaiming

除了 SciPy v0.11 引用指南,我找不到更多关于 scipy.sparse 索引的信息,它说

The lil_matrix class supports basic slicing and fancy indexing with a similar syntax to NumPy arrays.
. I have read numpy document about index, but I didn't understand it clearly, for example,

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

1. 为什么输出是

[[  0.  10.  10.] 
 [  0.   0.   0.] 
 [  0.   0.   0.]]

what does [0,1:3] meaning? if I use

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

出现错误:

IndexError: invalid index
,我不知道原因。

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

请您参考如下方法:

对于你的第二个问题,使用 nonzero() 方法。我不得不挖掘 the source找到它,因为我在任何引用文档中都找不到它。

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])) 
 
    """