What is the fastest way to slice a scipy.sparse matrix?

todpole3 picture todpole3 · Dec 12, 2012 · Viewed 17.3k times · Source

I normally use

matrix[:, i:]

It seems not work as fast as I expected.

Answer

Saullo G. P. Castro picture Saullo G. P. Castro · Jun 2, 2013

If you want to obtain a sparse matrix as output the fastest way to do row slicing is to have a csr type, and for columns slicing csc, as detailed here. In both cases you just have to do what you are currently doing:

matrix[l1:l2,c1:c2]

If you want another type as output there maybe faster ways. In this other answer it is explained many methods for slicing a matrix and their different timings compared. For example, if you want a ndarray as output the fastest slicing is:

matrix.A[l1:l2,c1:c2] 

or:

matrix.toarray()[l1:l2,c1:c2]

much faster than:

matrix[l1:l2,c1:c2].A #or .toarray()