Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numpy matrix to python array

Are there alternative or better ways to convert a numpy matrix to a python array than this?

>>> import numpy
>>> import array
>>> b = numpy.matrix("1.0 2.0 3.0; 4.0 5.0 6.0", dtype="float16")
>>> print(b)
[[ 1.  2.  3.]
 [ 4.  5.  6.]]
>>> a = array.array("f")
>>> a.fromlist((b.flatten().tolist())[0])
>>> print(a)
array('f', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
like image 606
lash Avatar asked Mar 06 '26 20:03

lash


2 Answers

You could convert to a NumPy array and generate its flattened version with .ravel() or .flatten(). This could also be achieved by simply using the function np.ravel itself as it does both these takes under the hood. Finally, use array.array() on it, like so -

a = array.array('f',np.ravel(b))

Sample run -

In [107]: b
Out[107]: 
matrix([[ 1.,  2.,  3.],
        [ 4.,  5.,  6.]], dtype=float16)

In [108]: array.array('f',np.ravel(b))
Out[108]: array('f', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
like image 119
Divakar Avatar answered Mar 09 '26 10:03

Divakar


here is an example :

>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
>>> x.tolist()
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
like image 43
muhanna hamiad Avatar answered Mar 09 '26 10:03

muhanna hamiad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!