Reputation: 2429
I would like to extract specific rows and columns from a scipy sparse matrix - probably lil_matrix
will be the best choice here.
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. 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. 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)?.
How can one accomplish this behaviour with a lil_matrix
?
My question is partly answered in slicing sparse (scipy) matrix, but I couldn't get this to work for lil_matrix
.
Upvotes: 4
Views: 3329
Reputation: 67437
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.
Upvotes: 4