如何YAML保存numpy数组

时间:2014-02-09 11:47:16

标签: python numpy save yaml

嗨有没有办法如何保存numpy 2D数组,然后从文件中安全地加载它? 我有这个数组:

     matrix = np.random.randint(2, size=(self.row,self.col))

但是我无法保存它

2 个答案:

答案 0 :(得分:8)

最明显的方法是安装pyyaml模块(Google App Engine使用),并将矩阵另存为列表。

import numpy as np
import yaml
matrix = np.random.randint(2, size=(10,7))
with open('stack21658676.yaml', 'w') as f:
    yaml.dump(matrix.tolist(), f)

with open('stack21658676.yaml') as f:
    loaded = yaml.load(f)
loaded = np.array(loaded)
print loaded

虽然我不得不问为什么你要YAML而不是'本地'numpy保存?

答案 1 :(得分:2)

In [24]: matrix = np.random.randint(2, size=(3,4))

In [25]: np.save('test', matrix)

In [26]: a = np.load('test.npy')

In [27]: matrix
Out[27]:
array([[0, 1, 1, 1],
       [1, 0, 1, 1],
       [1, 1, 1, 1]])

In [28]: a
Out[28]:
array([[0, 1, 1, 1],
       [1, 0, 1, 1],
       [1, 1, 1, 1]])