How to convert a 3D numpy array into a 3D sparse matrix in Python?

Viewed 1454

I have a 3D NumPy array that I want to convert to a 3D sparse matrix in Python. I looked up scipy.sparse module and only found 2D sparse matrix implementations. For example,

Input:

array([[[0],
        [0],
        [1],
        [0],
        [1],
        [0],
        [0]],
       [[1],
        [0],
        [1],
        [0],
        [0],
        [0],
        [0]]])

Output:

(0,0,2) 1
(0,0,4) 1
(0,1,0) 1
(0,1,2) 1

How would do this?

1 Answers

in n dimensions,you can find the indices with:

ind=np.array(np.where(a!=0)).T
#array([[0, 2, 0],
#       [0, 4, 0],
#       [1, 0, 0],
#       [1, 2, 0]], dtype=int64)

and the corresponding values for example with:

ravel_ind=np.apply_along_axis(ravel_multi_index,1,ind,a.shape)
values=np.take(a,ravel_ind)
# array([1, 1, 1, 1])  
Related