Numpy数组的保存与加载
Posted Xavier Jiezou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Numpy数组的保存与加载相关的知识,希望对你有一定的参考价值。
单个数组⇔二进制文件
将数组保存为二进制文件。推荐文件后缀.npy
。
>>> import numpy as np
>>> with open('test.npy', 'wb') as f:
... np.save(f, np.array([1, 2, 3]))
>>> with open('test.npy', 'rb') as f:
... a = np.load(f)
>>> a
array([1, 2, 3])
单个数组⇔文本文件(TXT)
将单个数组保存为文本(txt
)文件。可以直观地看到保存的数组。
>>> import numpy as np
>>> np.savetxt('test.txt', np.array([1, 2, 3]))
>>> a = np.genfromtxt('test.txt')
>>> a
array([1., 2., 3.])
多个数组⇔二进制文件(未压缩)
将多个数组以键值对的方式保存为二进制文件。推荐文件后缀.npz
。
>>> import numpy as np
>>> a = np.array([1])
>>> b = np.array([2])
>>> c = np.array([3])
>>> with open('test.npz', 'wb') as f:
... np.savez(f, a=a, b=b, c=c)
>>> with open('test.npz', 'rb') as f:
... a = np.load(f)['a']
... b = np.load(f)['b']
... c = np.load(f)['c']
>>> a
array([1])
>>> b
array([2])
>>> c
array([3])
多个数组⇔二进制文件(压缩)
将多个数组以键值对的方式保存为二进制压缩文件(使用的压缩算法是ZIP_DEFLATED)。推荐文件后缀.npz
。
>>> import numpy as np
>>> a = np.array([1])
>>> b = np.array([2])
>>> c = np.array([3])
>>> with open('test.npz', 'wb') as f:
... np.savez_compressed(f, a=a, b=b, c=c)
>>> with open('test.npz', 'rb') as f:
... a = np.load(f)['a']
... b = np.load(f)['b']
... c = np.load(f)['c']
>>> a
array([1])
>>> b
array([2])
>>> c
array([3])
以上是关于Numpy数组的保存与加载的主要内容,如果未能解决你的问题,请参考以下文章