http://blog.csdn.net/pipisorry/article/details/39088003
numpy数组基本输出
在屏幕上输出数组:print(mat1)
@contextmanager def np_printoptions(*args, **kwargs): ''' numpy本地应用打印选项,如: with np_printoptions(precision=3, suppress=True): print(x1) ''' original = np.get_printoptions() np.set_printoptions(*args, **kwargs) yield np.set_printoptions(**original)
NumPy提供了多种文件操作函数方便我们存取数组内容。
文件存取的格式:二进制和文本。二进制格式的文件又分为NumPy专用的格式化二进制类型和无格式类型。
1. tofile和fromfile数组内建函数(not recommend)
使用数组的方法函数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]])
Note:
1. 读入的时候设置正确的dtype和shape才能保证数据一致。并且tofile函数不管数组的排列顺序是C语言格式的还是Fortran语言格式的,统一使用C语言格式输出。
2. sep关键字参数:此外如果fromfile和tofile函数调用时指定了sep关键字参数的话,数组将以文本格式输入输出。{这样就可以通过notepad++打开查看, 不过数据是一行显示,不便于查看}
user_item_mat.tofile(user_item_mat_filename, sep=' ')
2. 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]])
Note:
1. 文件要保存为.npy文件类型,否则会出错
2. 保存为numpy专用二进制格式后,就不能用notepad++打开(乱码)看了,这是相对tofile内建函数不好的一点
3. numpy.savez函数
如果你想将多个数组保存到一个文件中的话,可以使用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的内容。
4. numpy.savetxt和numpy.loadtxt(推荐需要查看保存数据时使用)
使用numpy.savetxt和numpy.loadtxt可以读写1维和2维的数组:
>>> a = np.arange(0,12,0.5).reshape(4,-1) >>> np.savetxt("a.txt", a) # 缺省按照'%.18e'格式保存数据,以空格分隔 >>> np.loadtxt("a.txt") >>> 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.]])
Note:savetxt缺省按照'%.18e'格式保存数据, 可以修改保存格式为‘%.8f'(小数点后保留8位的浮点数), ’%d'(整数)等等
总结:
载入txt文件:numpy.loadtxt()/numpy.savetxt()
智能导入文本/csv文件:numpy.genfromtxt()/numpy.recfromcsv()
高速,有效率但numpy特有的二进制格式:numpy.save()/numpy.load()
文件名和文件对象
本节介绍所举的例子都是传递的文件名,也可以传递已经打开的文件对象.
例如对于load和save函数来说,如果使用文件对象的话,可以将多个数组储存到一个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])
numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=’‘, footer=’‘, comments=’#‘)
Save an array to a text file.
np.savetxt(输出文件名,矩阵名)
输出文件名应为二进制写入:
doc_word_mat_file = open('./filename.txt', 'wb')
否则出错:
savetxt(doc_word_mat_file, doc_word_mat) ... fh.write(asbytes(format % tuple(row) + newline))
TypeError: must be str, not bytes
所以推荐不要使用文件对象写入,用文件名写入