Search code examples
pythonnumpyscipysparse-matrix

Adding dimensions to scipy sparse


I wish to add a dimension to a sparse matrix. In numpy it's simply a matter of doing [:,None]. I tried reshape and resize without any success.

Here's some dummy data:

from scipy.sparse import csr_matrix

data = [1,2,3,4,5,6] 
col = [0,0,0,1,1,1] 
row = [0,1,2,0,1,2] 
a = csr_matrix((data, (row, col)))
a.reshape((3,2,1))

The last line gives the error: ValueError: matrix shape must be two-dimensional. Doing resize instead gives the error ValueError: shape must be a 2-tuple of positive integers.

In my particular case I also need to reshape it to (3,1,2). Any thoughts?


Solution

  • scipy.sparse can only handle 2d arrays. You might want to look into pydata/sparse which looks to handle n-dimensional sparse data while following the array interface. At the moment, it has fewer types of arrays and will have some performance issues, but is being actively developed.