[SciPy-user] Iteration over scipy.sparse matrices?
Nathan Bell
wnbell@gmail....
Thu May 1 16:40:05 CDT 2008
On Thu, May 1, 2008 at 4:32 PM, Nathan Bell <wnbell@gmail.com> wrote:
> for i,j,v in zip(A.row, A.col, A.data):
> print "row = %d, column = %d, value = %s" % (i,j,v)
I should mention that since A.row, A.col, and A.data are all numpy
arrays you can often vectorize sparse computations with them.
For instance, suppose we wanted to eliminate all entries of a
coo_matrix A that are less than 5 and store the result in a matrix B:
A = coo_matrix(....)
mask = A.data < 5
B = coo_matrix( (data[mask],(row[mask],col[mask])), shape=A.shape)
As another example, extract all the entries above the diagonal:
A = coo_matrix(....)
mask = A.col > A.row
B = coo_matrix( (data[mask],(row[mask],col[mask])), shape=A.shape)
Since conversions to and from the COO format are quite fast, you can
use this approach to efficiently implement lots computations on sparse
matrices.
--
Nathan Bell wnbell@gmail.com
http://graphics.cs.uiuc.edu/~wnbell/
More information about the SciPy-user
mailing list