前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python如何保存矩阵,保存matrix,保存numpy.ndarray

python如何保存矩阵,保存matrix,保存numpy.ndarray

作者头像
学到老
发布2018-04-02 14:43:47
13K0
发布2018-04-02 14:43:47
举报

问题:如何将array保存到txt文件中?如何将存到txt文件中的数据读出为ndarray类型?python如何保存矩阵,保存matrix,保存numpy.ndarray

分析

代码语言:javascript
复制
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]])  

有些时候会报错:TypeError: Mismatch between array dtype (‘object’) and format specifier (‘%.18e’) 其中format specifier (‘%.18e’)表示传入的格式, 常用的有%d,%s

代码语言:javascript
复制
 fmt : str or sequence of strs, optional
        A single format (%10.5f), a sequence of formats, or a
        multi-format string, e.g. 'Iteration %d -- %10.5f', in which
        case `delimiter` is ignored. For complex `X`, the legal options
        for `fmt` are:
            a) a single specifier, `fmt='%.4e'`, resulting in numbers formatted
                like `' (%s+%sj)' % (fmt, fmt)`
            b) a full string specifying every real and imaginary part, e.g.
                `' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns
            c) a list of specifiers, one per column - in this case, the real
                and imaginary part must have separate specifiers,
                e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns
代码语言:javascript
复制
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.]])  

案例:

代码语言:javascript
复制
trainMat=[[1,1,1],[1,0,2,0,1],[1,2,3,4]]
numpy.savetxt("filename.txt",trainMat,fmt="%s",delimiter=",")
这里写图片描述
这里写图片描述

但是在加载过程中会报错!

代码语言:javascript
复制
c=numpy.loadtxt("filename.txt",delimiter=",",skiprows=0,dtype=int)
这里写图片描述
这里写图片描述

如果处理下:加个b

代码语言:javascript
复制
c=numpy.loadtxt(b"filename.txt",delimiter=",",skiprows=0,dtype=int)

返回的结果反而变了,当成了一个数组,因此,在用loadtxt适用于1维

这里写图片描述
这里写图片描述

结论:

Numpy能够读写磁盘上的文本数据或二进制数据。 存取文本文件

np.loadtxt和np.savetxt可以读写1维和2维的数组:

同时可以指定各种分隔符、针对特定列的转换器函数、需要跳过的行数等。

np.loadtxt(FILENAME, dtype=int, delimiter=’ ‘) np.savetxt(“a.txt”, a, fmt=”%d”, delimiter=”,”)

例子:

代码语言:javascript
复制
a=np.arange(0,10).reshape(2,-1)
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
np.savetxt("a.txt",a) #缺省按照'%.18e'格式保存数据,以空格分隔
np.loadtxt("a.txt")
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.]])

a=np.arange(0,10,0.5).reshape(4,-1)

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]])
np.savetxt("a.txt",a,fmt="%d",delimiter=",")#改为保存为整数,以逗号分隔
np.loadtxt("a.txt",delimiter=",")#load时也要指定为逗号分隔
array([[ 0.,  0.,  1.,  1.,  2.],
       [ 2.,  3.,  3.,  4.,  4.],
       [ 5.,  5.,  6.,  6.,  7.],
       [ 7.,  8.,  8.,  9.,  9.]])

np.savez 多个数组保存

如果你想将多个数组保存到一个文件中的话,可以使用numpy.savez函数。savez函数的第一个参数是文件名,其后的参数都是需要保存的数组,也可以使用关键字参数为数组起一个名字,非关键字参数传递的数组会自动起名为arr_0, arr_1, …。savez函数输出的是一个压缩文件(扩展名为npz),其中每个文件都是一个save函数保存的npy文件,文件名对应于数组名。load函数自动识别npz文件,并且返回一个类似于字典的对象,可以通过数组名作为关键字获取数组的内容:

代码语言:javascript
复制
>>> C=np.array([1,0,1,0])
>>> np.savez("files.npz",A,B,C_array=C)
>>> D=np.load("files.npz")
>>> D['arr_0']
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> D['arr_1']
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> D['arr_2']
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "D:\Python3\lib\site-packages\numpy\lib\npyio.py", line 255, in __getitem__
    raise KeyError("%s is not a file in the archive" % key)
KeyError: 'arr_2 is not a file in the archive'
>>> D['C_array']
array([1, 0, 1, 0])

如果你用解压软件打开files.npz文件的话,会发现其中有三个文件:arr_0.npy, arr_1.npy, C_array.npy,其中分别保存着数组A,B,C的内容

np.load和np.save将数组以二进制格式保存到磁盘

np.load和np.save是读写磁盘数组数据的两个主要函数,默认情况下,数组是以未压缩的原始二进制格式保存在扩展名为.npy的文件中。

代码语言:javascript
复制
>>> import numpy as np
A = np.arange(15).reshape(3,5)
>>> A
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> np.save("A.npy",A)   #如果文件路径末尾没有扩展名.npy,该扩展名会被自动加上。
>>> B=np.load("A.npy")
>>> B
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

注:保存为Numpy专用的二进制格式后,就不能用notepad++等打开看了(乱码)。因此这种方式建议在不需要看保存文件内容的情况下使用。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年03月20日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 分析
  • 结论:
    • np.loadtxt和np.savetxt可以读写1维和2维的数组:
      • np.savez 多个数组保存
        • np.load和np.save将数组以二进制格式保存到磁盘
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档