is it possible to stack a sparse and a dense numpy array in python? I know this can be done for dense numpy arrays using vstack/hstack. I have some columns that I would like to add to a sparse matrix in order to increase the number of feature vectors
1 Answers
11
votes
Yes, you can use scipy.sparse.vstack
and scipy.sparse.hstack
, in the same way as you would use numpy.vstack
and numpy.hstack
for dense arrays.
Example:
from scipy.sparse import coo_matrix
m = coo_matrix(np.array([[0,0,1],[1,0,0],[1,0,0]]))
a = np.ones(m.shape)
With np.vstack
:
np.vstack((a,m))
#ValueError: all the input array dimensions except for the concatenation axis must match exactly
With scipy.sparse.vstack
:
scipy.sparse.vstack((a,m))
#<6x3 sparse matrix of type '<type 'numpy.float64'>'
# with 12 stored elements in COOrdinate format>