5

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?

4
  • Possible duplicate of How to transform numpy.matrix or array to scipy sparse matrix Commented Sep 6, 2018 at 4:30
  • 2
    Hi Lucas, I tried it already. They expect a dimension of 2 or less than 2. In my case, the dimension of the array is 3. Commented Sep 6, 2018 at 4:32
  • 3
    As you note the scipy.sparse code only works with 2d. What do you want to do with the sparse matrix once you have it? It's one thing to represent the values, it's quite another to do something meaningful with them. Commented Sep 6, 2018 at 5:24
  • 2
    Yeah, it's fairly simple to create a dok or lil implementation in 3d, but without the algorithms that let csr and csc implementations do matrix math, they won't be particularly useful. If the matrix is some sort of transfer function you would probably be better flattening the input and output and storing the transformation in 2D. This is how, for example, a 4D symmetric transform can be represented in 2D via Voigt Notation Commented Sep 6, 2018 at 6:13

1 Answer 1

0

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])  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.