[英]scipy: how to get all non-zero value index for each row?
I can't find more info about scipy.sparse indexing except SciPy v0.11 Reference Guide, which says that 除了《 SciPy v0.11参考指南》,我找不到有关scipy.sparse索引的更多信息。
The lil_matrix class supports basic slicing and fancy indexing with a similar syntax to NumPy arrays..
Asp = sparse.lil_matrix((3,3)) Asp.setdiag(zeros(3)) Asp[0, 1:3] = 10 print Asp.todense()
1. why the output is 1.为什么输出
[[ 0. 10. 10.][[0. 10. 10.]\n [ 0. 0. 0.]
[0. 0. 0.]\n [ 0. 0. 0.]]
[0. 0. 0.]]
what does [0,1:3] meaning? [0,1:3]是什么意思? if I use
如果我用
Asp[0, 1:2,3] = 10
there's a error: 有一个错误:
IndexError: invalid index, I don't know the reason.IndexError:无效的索引
2.what's the fastest way to get all non-zero values for each row? 2.什么是最快获取每一行所有非零值的方法?
For your second question, use the nonzero()
method. 对于第二个问题,请使用
nonzero()
方法。 I had to dig through the source to find it, since I couldn't find it in any of the reference documentation. 我必须仔细研究源代码才能找到它,因为在任何参考文档中都找不到。
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]))
"""
what does
[0,1:3]
mean?[0,1:3]
是什么意思?
That means: row 0, elements 1
to 3
(exclusive). 这意味着:第0行,元素
1
至3
(不包括)。 Since Numpy and Scipy use zero-based indices, row 0 is the first row and 1:3
denotes the first and second column. 由于Numpy和Scipy使用从零开始的索引,因此第0行是第一行,而
1:3
表示第一列和第二列。
Asp[0, 1:2,3]
is invalid because you've got three indices, 0
, 1:2
and 3
. Asp[0, 1:2,3]
无效,因为您有三个索引0
1:2
和3
。 Matrices only have two axes. 矩阵只有两个轴。
This is all standard Numpy stuff; 这是所有标准的Numpy内容; read any good tutorial on that package.
阅读有关该软件包的任何优秀教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.