[英]Slicing a scipy.sparse.lil_matrix in rows and columns
I would like to extract specific rows and columns from a scipy sparse matrix - probably lil_matrix
will be the best choice here. 我想从scipy稀疏矩阵中提取特定的行和列 - 可能
lil_matrix
将是这里的最佳选择。
It works fine here: 它在这里工作正常:
from scipy import sparse
lilm=sparse.lil_matrix((10,10))
lilm[0:4,0:3]
This returns a 4x3 sparse matrix. 这将返回4x3稀疏矩阵。 I don't want a block from the matrix though, but rather single columns and rows.
我不希望矩阵中的块,而是单个列和行。 I'd expect this to work:
我希望这可行:
lilm[[1,2,3],[4,5,6]]
but it returns a 1x3 sparse matrix. 但它返回1x3稀疏矩阵。 This also doesn't work with numpy arrays, but there you can use numpy.ix_, as described in Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?
这也适用于numpy数组,但你可以使用numpy.ix_,如切片NumPy 2d数组中所述,或者如何从nxn数组(n> m)中提取mxm子矩阵? .
。
How can one accomplish this behaviour with a lil_matrix
? 如何用
lil_matrix
实现这种行为?
My question is partly answered in slicing sparse (scipy) matrix , but I couldn't get this to work for lil_matrix
. 我的问题在切片稀疏(scipy)矩阵中得到了部分回答,但是我无法
lil_matrix
适用于lil_matrix
。
You will need to first extract the rows, then the columns: 您需要先提取行,然后是列:
>>> a = np.arange(100).reshape(10, 10)
>>> a
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
>>> lilm = scipy.sparse.lil_matrix(a)
>>> lilm[[1, 2, 3], :].toarray() # extract the rows first...
array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]])
>>> lilm[[1, 2, 3], :][:, [4, 5, 6]].toarray() # ...then the columns
array([[14, 15, 16],
[24, 25, 26],
[34, 35, 36]])
You would of course remove the .toarray()
from this last expression to get the return as a LIL sparse matrix. 您当然会从最后一个表达式中删除
.toarray()
以获得作为LIL稀疏矩阵的返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.