[SciPy-user] Iteration over scipy.sparse matrices?
Thu May 1 16:32:11 CDT 2008
On Thu, May 1, 2008 at 2:54 PM, Joseph Turian <email@example.com> wrote:
> Is there a (storage-format agnostic) method for iterating over the elements
> of a sparse matrix?
> I don't care what order they come in. I just want to make sure that I can
> iterate over the matrix in time linear in nnz, and have the (row, col) and
> data for each non-zero entry.
In the current SVN version of SciPy all sparse matrices may be
converted to the "coordinate" format using the .tocoo() member
function. Alternatively, one may pass any matrix (sparse or dense) to
the coo_matrix constructor.
Using the COO format makes iteration trivial:
M = .... #sparse or dense matrix
A = coo_matrix(M)
for i,j,v in zip(A.row, A.col, A.data):
print "row = %d, column = %d, value = %s" % (i,j,v)
Some sparse matrices support a rowcol() method that does something
similar without making a conversion. However, rowcol() will
deprecated in the next release since it's much slower than doing a
Nathan Bell firstname.lastname@example.org
More information about the SciPy-user