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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With