python - 将 numpy 矩阵转换为 python 数组

标签 python arrays numpy

是否有替代或更好的方法将 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])

最佳答案

您可以转换为 NumPy array并使用 .ravel().flatten() 生成其扁平化版本。这也可以通过简单地使用函数 np.ravel 来实现。本身,因为它在这两个方面都处于幕后。最后,使用 array.array()在上面,就像这样 -

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

sample 运行-

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

关于python - 将 numpy 矩阵转换为 python 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39016638/

相关文章:

python - 用于拉伸(stretch)/压缩音频文件以在 python 中具有预设数量的样本的功能?

python - 刚性 ODE 求解器

python - 从数组中删除元素

python - 具有可能重复项的 numpy 数组的排名

python - sparse_hash_map 对于特定数据非常慢

Python 数据将行格式化为列

python - wexpect 语法错误

javascript - 合并多维数组中重复的数组键

arrays - 包含打开文件路径引用的数组

ruby - 检查整数数组是否在 Ruby 中递增