您的位置:首页 > 编程语言 > Python开发

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

2018-03-20 17:40 489 查看
问题:如何将array保存到txt文件中?如何将存到txt文件中的数据读出为ndarray类型?python如何保存矩阵,保存matrix,保存numpy.ndarray

python中list、array、matrix之间的基本区别:直通车

分析

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

fmt : str or sequence of strs, optional
A single format (%10.5f), a sequence of formats, or a
multi-f
4000
ormat 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


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.]])


案例:

trainMat=[[1,1,1],[1,0,2,0,1],[1,2,3,4]]
numpy.savetxt("filename.txt",trainMat,fmt="%s",delimiter=",")




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

c=numpy.loadtxt("filename.txt",delimiter=",",skiprows=0,dtype=int)




如果处理下:加个b

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=”,”)

例子:

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文件,并且返回一个类似于字典的对象,可以通过数组名作为关键字获取数组的内容:

>>> 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的文件中。

>>> 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++等打开看了(乱码)。因此这种方式建议在不需要看保存文件内容的情况下使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: