Numpy学习(1)numpy文件存取
NumPy提供了多种文件操作函数方便我们存取数组内容。文件存取的格式分为两类:二进制和文本。而二进制格式的文件又分为NumPy专用的格式化二进制类型和无格式类型。
一、tofile()和fromfile()
使用数组的方法函数tofile可以方便地将数组中数据以二进制的格式写进文件。tofile输出的数据没有格式,因此用numpy.fromfile读回来的时候需要自己格式化数据:
>>> 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") >>> b = np.fromfile("a.bin", dtype=np.float) # 按照float类型读入数据 >>> b # 读入的数据是错误的 array([ 2.12199579e-314, 6.36598737e-314, 1.06099790e-313, 1.48539705e-313, 1.90979621e-313, 2.33419537e-313]) >>> a.dtype # 查看a的dtype dtype("int32") >>> b = np.fromfile("a.bin", dtype=np.int32) # 按照int32类型读入数据 >>> b # 数据是一维的 array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) >>> b.shape = 3, 4 # 按照a的shape修改b的shape >>> b # 这次终于正确了 array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
从上面的例子可以看出,需要在读入的时候设置正确的dtype和shape才能保证数据一致。并且tofile函数不管数组的排列顺序是C语言格式的还是Fortran语言格式的,统一使用C语言格式输出。
此外如果fromfile和tofile函数调用时指定了sep关键字参数的话,数组将以文本格式输入输出。
二、save()和load()
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") >>> r["arr_0"] # 数组a array([[1, 2, 3], [4, 5, 6]]) >>> r["arr_1"] # 数组b array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) >>> r["sin_array"] # 数组c 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的内容。
save()和savez()输出的二进制文件有特殊的格式,较难用其它语言编写的程序读入。
三、savetxt()和loadtxt()
使用numpy.savetxt和numpy.loadtxt可以读写1维和2维的数组或者CSV文件:
>>> a = np.arange(0,12,0.5).reshape(4,-1) >>> np.savetxt("a.txt", a) # 缺省按照"%.18e"格式保存数值,以空格分隔 >>> 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.]])有的CSV文件中除了保存数值之外,还保存一些说明文字,例如第一行和第一列通常为列名和行名。如果需要忽略CSV文件的第一行和第一列,可以先将文件读为字符串数组,然后取出需要的部分再转换为数值数组。例如对于下面的CSV数据文件:
姓名,年龄,体重,身高 张三,30,75,165 李四,45,60,170 王五,15,30,120可以采用如下的程序读入其中的数值部分:
# -*- coding: utf-8 -*- """ 使用NumPy快速读取CSV文件。 """ import numpy as np # 采用字符串数组读取文件 tmp = np.loadtxt("test.csv", dtype=np.str, delimiter=",") # 将部分数组的值进行转换 data = tmp[1:,1:].astype(np.float) print data # 定义结构数组元素的类型 persontype = np.dtype({ "names":["name", "age", "weight", "height"], "formats":["S32","i", "f", "f"]}) f = file("test.csv") f.readline() # 跳过第一行 data = np.loadtxt(f, dtype=persontype, delimiter=",") f.close() print data
读取CSV文件:
>>> tmp = np.loadtxt("test.csv", dtype=np.str, delimiter=",") >>> data = tmp[1:,1:].astype(np.float) >>> data array([[ 30., 75., 165.], [ 45., 60., 170.], [ 15., 30., 120.]])此外,使用结构数组也能读入这样的文件,并且可以使用不同的元素类型保存每个列的值,下面先定义结构数组的类型:
>>> persontype = np.dtype({ ... "names":["name", "age", "weight", "height"], ... "formats":["S32","i", "f", "f"]})由于文件中的第一行不是数据,因此需要先打开数据文件,读取完第一行之后,再把文件对象传递给loadtxt():
>>> f = file("test.csv") >>> f.readline() >>> data = np.loadtxt(f, delimiter=",", dtype=persontype) >>> print data [("xe5xbcxa0xe4xb8x89", 30, 75.0, 165.0) ("xe6x9dx8exe5x9bx9b", 45, 60.0, 170.0) ("xe7x8ex8bxe4xbax94", 15, 30.0, 120.0)]
四、文件对象file
实际上,前面介绍的所有读写文件的函数都可以直接使用已经打开的文件对象,如果使用文件对象,可以将多个数组储存到一个npy文件中:
>>> a = np.arange(8) >>> b = np.add.accumulate(a) >>> c = a + b >>> f = file("result.npy", "wb") >>> np.save(f, a) # 顺序将a,b,c保存进文件对象f >>> np.save(f, b) >>> np.save(f, c) >>> f.close() >>> f = file("result.npy", "rb") >>> np.load(f) # 顺序从文件对象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])
参考链接:
1. http://old.sebug.net/paper/books/scipydoc/numpy_intro.html#id9
2. http://www.cnblogs.com/dmir/p/5009075.html
- 上一篇:没有了
- 下一篇: java中字符串与数组之间的转换