A fast way to find nonzero entries by row in a sparse matrix in Python

matrix, numpy, python

Solution

Use the `.nonzero()` method.

indices = sp_matrix.nonzero()

If you'd like the indices as `(row, column)` tuples, you can use `zip`.

indices = zip(*sp_matrix.nonzero())

Problem

I am trying to find the indices of nonzero entries by row in a sparse matrix: scipy.sparse.csc_matrix. So far, I am looping over each row in the matrix, and using ``` numpy.nonzero() ``` to each row to get the nonzero column indices. But this method would take over an hour to find the nonzero column entries per row. Is there a fast way to do so? Thanks!

Original source