简体   繁体   English

将numpy矩阵转换为python数组

[英]Convert numpy matrix to python array

Are there alternative or better ways to convert a numpy matrix to a python array than this? 是否有替代或更好的方法将numpy矩阵转换为python数组?

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

You could convert to a NumPy array and generate its flattened version with .ravel() or .flatten() . 您可以转换为NumPy array并使用.ravel().flatten()生成其展平版本。 This could also be achieved by simply using the function np.ravel itself as it does both these takes under the hood. 这也可以通过简单地使用函数np.ravel本身来实现,因为它可以在引擎盖下进行。 Finally, use array.array() on it, like so - 最后,在它上面使用array.array() ,就像这样 -

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM