2016-08-18 3 views
2

Gibt es alternative oder bessere Möglichkeiten, eine numpy Matrix zu einem Python-Array als das zu konvertieren?Konvertieren numpy Matrix in Python-Array

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

Antwort

1

Sie auf ein NumPy array umwandeln könnte und erzeugen ihre abgeflachten Version mit .ravel() oder .flatten(). Dies könnte auch erreicht werden, indem einfach die Funktion np.ravel selbst verwendet wird, da dies beides unter der Haube geschieht. Schließlich verwenden array.array() darauf, wie so -

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

Probelauf -

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]) 
-1

hier ein Beispiel:

>>> 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]]