Iterating through a scipy.sparse vector (or matrix)

Edit: bbtrb’s method (using coo_matrix) is much faster than my original suggestion, using nonzero. Sven Marnach’s suggestion to use itertools.izip also improves the speed. Current fastest is using_tocoo_izip: import scipy.sparse import random import itertools def using_nonzero(x): rows,cols = x.nonzero() for row,col in zip(rows,cols): ((row,col), x[row,col]) def using_coo(x): cx = scipy.sparse.coo_matrix(x) for i,j,v in zip(cx.row, cx.col, … Read more

Concatenate sparse matrices in Python using SciPy/Numpy

You can use the scipy.sparse.hstack to concatenate sparse matrices with the same number of rows (horizontal concatenation): from scipy.sparse import hstack hstack((X, X2)) Similarly, you can use scipy.sparse.vstack to concatenate sparse matrices with the same number of columns (vertical concatenation). Using numpy.hstack or numpy.vstack will create an array with two sparse matrix objects.