import numpy as np
a = np.arange(0,12)
a.shape = 3,4
a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
a.tofile("a.bin")
按照 float 类型读入数据
b = np.fromfile("a.bin", dtype=float)
读入的数据是错误的
b
array([0.0e+000, 4.9e-324, 9.9e-324, 1.5e-323, 2.0e-323, 2.5e-323,
3.0e-323, 3.5e-323, 4.0e-323, 4.4e-323, 4.9e-323, 5.4e-323])
查看 a 的 dtype
a.dtype
dtype('int64')
按照 int32 类型读入数据
b = np.fromfile("a.bin", dtype=np.int64)
数据是一维的
b
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
按照 a 的 shape 修改b的 shape
b.shape = 3, 4
这次终于正确了
b
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
从上面的例子可以看出,需要在读入的时候设置正确的 dtype 和 shape 才能保证数据一致。
并且 tofile 函数不管数组的排列顺序是C语言格式的还是Fortran语言格式的,统一使用C语言格式输出。
此外如果 fromfile 和 tofile 函数调用时指定了 sep 关键字参数的话,数组将以文本格式输入输出。
numpy.load 和 numpy.save 函数以NumPy专用的二进制类型保存数据,
这两个函数会自动处理元素类型和 shape 等信息,使用它们读写数组就方便多了,
但是 numpy.save 输出的文件很难和其它语言编写的程序读入:
np.save("a.npy", a)
c = np.load( "a.npy" )
c
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
如果想将多个数组保存到一个文件中的话,可以使用 numpy.savez 函数。
savez 函数的第一个参数是文件名,其后的参数都是需要保存的数组,
也可以使用关键字参数为数组起一个名字,非关键字参数传递的数组会自动起名为 arr_0, arr_1, ...。
savez 函数输出的是一个压缩文件(扩展名为 npz ),
其中每个文件都是一个 save 函数保存的 npy 文件,文件名对应于数组名。
load 函数自动识别 npz 文件,并且返回一个类似于字典的对象,
可以通过数组名作为关键字获取数组的内容:
a = np.array([[1,2,3],[4,5,6]])
b = np.arange(0, 1.0, 0.1)
c = np.sin(b)
np.savez("result.npz", a, b, sin_array = c)
r = np.load("result.npz")
数组a
r["arr_0"]
array([[1, 2, 3],
[4, 5, 6]])
数组b
r["arr_1"]
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
数组c
r["sin_array"]
array([0. , 0.09983342, 0.19866933, 0.29552021, 0.38941834,
0.47942554, 0.56464247, 0.64421769, 0.71735609, 0.78332691])
如果用解压软件打开 result.npz 文件的话,会发现其中有三个文件:
arr_0.npy, arr_1.npy, sin_array.npy,其中分别保存着数组a, b, c的内容。
使用 numpy.savetxt 和 numpy.loadtxt 可以读写1维和2维的数组:
a = np.arange(0,12,0.5).reshape(4,-1)
缺省按照 '%.18e' 格式保存数据,以空格分隔
np.savetxt("a.txt", a)
np.loadtxt("a.txt")
array([[ 0. , 0.5, 1. , 1.5, 2. , 2.5],
[ 3. , 3.5, 4. , 4.5, 5. , 5.5],
[ 6. , 6.5, 7. , 7.5, 8. , 8.5],
[ 9. , 9.5, 10. , 10.5, 11. , 11.5]])
改为保存为整数,以逗号分隔
np.savetxt("a.txt", a, fmt="%d", delimiter=",")
读入的时候也需要指定逗号分隔
np.loadtxt("a.txt",delimiter=",")
array([[ 0., 0., 1., 1., 2., 2.],
[ 3., 3., 4., 4., 5., 5.],
[ 6., 6., 7., 7., 8., 8.],
[ 9., 9., 10., 10., 11., 11.]])
本节介绍所举的例子都是传递的文件名,也可以传递已经打开的文件对象,
例如对于 load 和 save 函数来说,如果使用文件对象的话,
可以将多个数组储存到一个 npy 文件中:
a = np.arange(8)
b = np.add.accumulate(a)
c = a + b
f = open("result.npy", "wb")
顺序将a,b,c保存进文件对象f
np.save(f, a)
np.save(f, b)
np.save(f, c)
f.close()
f = open("result.npy", "rb")
顺序从文件对象 f 中读取内容
np.load(f)
array([0, 1, 2, 3, 4, 5, 6, 7])
np.load(f)
array([ 0, 1, 3, 6, 10, 15, 21, 28])
np.load(f)
array([ 0, 2, 5, 9, 14, 20, 27, 35])