python - How to convert a scipy row matrix into a numpy array -
consider following example:
import numpy np import scipy.sparse = scipy.sparse.csr_matrix((2,2)) b = a.sum(axis=0)
the matrix b
has form
matrix([[ 0., 0.]])
however, i'd become array this:
array([ 0., 0.])
this can done b = np.asarray(b)[0]
, not seem elegant, compared matlab's b(:)
. there more elegant way this?
b.a1
job.
in [83]: out[83]: <2x2 sparse matrix of type '<class 'numpy.float64'>' 0 stored elements in compressed sparse row format> in [84]: a.a out[84]: array([[ 0., 0.], [ 0., 0.]]) in [85]: b=a.sum(axis=0) in [86]: b out[86]: matrix([[ 0., 0.]]) in [87]: b.a1 out[87]: array([ 0., 0.]) in [88]: a.a.sum(axis=0) # way out[88]: array([ 0., 0.])
you can vote this, or add top grossing answer here: numpy matrix array :)
a
sparse matrix. sparse sum performed matrix product (an appropriate matrix of 1s). result dense matrix.
sparse matrix has toarray()
method, .a
shortcut.
dense matrix has those, has .a1
(poorly documented - hence hits), flattens well.
the doc a1
:
return `self` flattened `ndarray`. equivalent ``np.asarray(x).ravel()``
in fact code is
return self.__array__().ravel()
====================
is matlab b(:)
equivalent?
a(:) elements of a, regarded single column.
if read correctly, numpy
equivalent transpose, or b.ravel().t
. shape (2,1). in matlab column matrix simplest form of matrix.
in [94]: b.t out[94]: matrix([[ 0.], [ 0.]])
(i'm old matlab programmer, octave on standby computer. , copy of 3.5 on old windows disk. :) ).
Comments
Post a Comment