5

I really couldn't google it. How to transform sparse matrix to ndarray?

Assume, I have sparse matrix t of zeros. Then

g = t.todense()
g[:10] 

matrix([[0],
    [0],
    [0],
    [0],
    [0],
    [0],
    [0],
    [0],
    [0],
    [0]])

instead of [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Solution:

t.toarray().flatten()

1
  • you can use .toarray() instead... Commented Jul 15, 2014 at 11:31

2 Answers 2

3

Use np.asarray:

>>> a = np.asarray(g)
>>> a
array([[0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [0]])

Where g is your dense matrix in the example (after calling t.todense()).

You specifically asked for the output of

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

which has only one dimension. To get that, you'll want to flatten the array:

>>> flat_array = np.asarray(g).flatten()
>>> flat_array
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Edit:

You can skip straight to the array from the sparse matrix with:

a = t.toarray()
Sign up to request clarification or add additional context in comments.

Comments

0

Transpose your matrix to convert first column to first row

g = g.T

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.