Numpy: Transform sparse matrix to ndarray

matrix, numpy, python, sparse-matrix

Solution

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()

Problem

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()

Original source