NumPy库学习笔记(8) NumPy的文件存取(1维2维和更高维度的数组)

参考链接: NumPy官网

参考链接: NumPy: the absolute basics for beginners

参考链接: Quickstart tutorial

参考链接: Broadcasting广播

参考链接: NumPy 中文教程

参考链接: Python数据分析与展示

首先处理一维和二维的数据
CSV只能有效存储一维和二维数组
np.savetxt() np.loadtxt()只能有效存取一维和二维数组

保存文件:

  • np.savetxt(frame, array, fmt=’%.18e’, delimiter=None)
    • frame : 文件、字符串或产生器,可以是.gz或.bz2的压缩文件
    • array : 存入文件的数组
    • fmt : 写入文件的格式,例如:%d %.2f %.18e
    • delimiter : 分割字符串,默认是任何空格

加载文件:

  • np.loadtxt(frame, dtype=np.float, delimiter=None, unpack=False)
    • frame : 文件、字符串或产生器,可以是.gz或.bz2的压缩文件
    • dtype : 数据类型,可选
    • delimiter : 分割字符串,默认是任何空格
    • unpack : 如果True,读入属性将分别写入不同变量

实验代码展示:

Microsoft Windows [版本 10.0.18363.1198]
(c) 2019 Microsoft Corporation。保留所有权利。

C:\Users\chenxuqi>cd C:\Users\chenxuqi\Desktop\numpy学习资料\Experiments4NumPy

C:\Users\chenxuqi\Desktop\numpy学习资料\Experiments4NumPy>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a = np.arange(10).reshape(2,5)
>>> a
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> np.savetxt("a整数.csv",a,fmt="%d",delimiter=",")
>>> np.savetxt("a浮点数(两位小数).csv",a,fmt="%.2f",delimiter=",")
>>> np.savetxt("a浮点数(三位小数).csv",a,fmt="%.3f",delimiter=",")
>>> # 分隔符默认是空格
...
>>> np.savetxt("a整数(使用默认分隔符).csv",a,fmt="%d")
>>> np.savetxt("a浮点数(科学计数法).csv",a,fmt='%.18e',delimiter=",")
>>> #####################################################
... # 以下是读取文件
... b = np.loadtxt("a整数.csv",delimiter=",")
>>> b
array([[0., 1., 2., 3., 4.],
       [5., 6., 7., 8., 9.]])
>>> b = np.loadtxt("a整数.csv",delimiter=",")
>>> b
array([[0., 1., 2., 3., 4.],
       [5., 6., 7., 8., 9.]])
>>> b = np.loadtxt("a整数.csv",delimiter=",",dtype=np.int)
>>> b
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> b = np.loadtxt("a浮点数(科学计数法).csv",delimiter=",",dtype=np.int)
>>> b
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> b = np.loadtxt("a浮点数(科学计数法).csv",delimiter=",",dtype=np.float)
>>> b
array([[0., 1., 2., 3., 4.],
       [5., 6., 7., 8., 9.]])
>>> b = np.loadtxt("a整数(使用默认分隔符).csv",delimiter=None,dtype=np.int)
>>> b
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> b = np.loadtxt("a整数(使用默认分隔符).csv",dtype=np.int)
>>> b
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>>
>>> a
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> np.savetxt("a浮点数(5位科学计数法).csv",a,fmt='%.5e',delimiter=",")
>>>
>>>

生成的相关文件内容截图:
在这里插入图片描述

多维数据的保存和读取:

需要注意:该方法需要读取时知道存入文件时数组的维度和元素类型,a.tofile()和np.fromfile()需要配合使用,可以通过元数据文件来存储额外信息

保存文件:

  • a.tofile(frame, sep=’’, format=’%s’)
    • frame : 文件、字符串
    • sep : 数据分割字符串,如果是空串,写入文件为二进制
    • format : 写入数据的格式

读取文件:

  • np.fromfile(frame, dtype=float, count=‐1, sep=’’)
    • frame : 文件、字符串
    • dtype : 读取的数据类型
    • count : 读入元素个数,‐1表示读入整个文件
    • sep : 数据分割字符串,如果是空串,写入文件为二进制

实验代码展示:

Microsoft Windows [版本 10.0.18363.1198]
(c) 2019 Microsoft Corporation。保留所有权利。

C:\Users\chenxuqi>cd C:\Users\chenxuqi\Desktop\numpy学习资料\Experiments4NumPy

C:\Users\chenxuqi\Desktop\numpy学习资料\Experiments4NumPy>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>> a.tofile("b(逗号和字符串).dat",sep=",",format="%s")
>>> a.tofile("b(逗号以及两位浮点数).dat",sep=",",format="%.2f")
>>> a.tofile("b(逗号和整数).dat",sep=",",format="%d")
>>> a.tofile("b(默认空串表示二进制文件和整数).dat",format="%d")
>>> a.tofile("b(空字符串表示二进制文件和整数).dat",format="%d",sep="")
>>> c_str = np.fromfile("b(逗号和字符串).dat",sep=",") # 默认将读入的数据转为float64类型
>>> c_str,c_str.dtype
(array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12.,
       13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23.]), dtype('float64'))
>>> # c_str = np.fromfile("b(逗号和字符串).dat",dtype=np.int,sep=" ") # 分隔符一定要指明正确
... c_str = np.fromfile("b(逗号和字符串).dat",dtype=np.int,sep=",")
>>>
>>> c_str = np.fromfile("b(逗号和字符串).dat",dtype=np.int,sep=",")
>>> c_str,c_str.dtype
(array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23]), dtype('int32'))
>>> c_str2float = np.fromfile("b(逗号和字符串).dat",dtype=np.float,sep=",")
>>> c_str2float.dtype,c_str2float
(dtype('float64'), array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12.,
       13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23.]))
>>> c_binary2int = np.fromfile("b(默认空串表示二进制文件和整数).dat",dtype=np.int)
>>> c_binary2int.dtype,c_binary2int
(dtype('int32'), array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23]))
>>> c_binary2int = np.fromfile("b(空字符串表示二进制文件和整数).dat",dtype=np.int)
>>> c_binary2int,c_binary2int.dtype
(array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23]), dtype('int32'))
>>> c_binary2float = np.fromfile("b(默认空串表示二进制文件和整数).dat",dtype=np.float)
>>> c_binary2float # 这里数据读取有问题
array([2.12199579e-314, 6.36598737e-314, 1.06099790e-313, 1.48539705e-313,
       1.90979621e-313, 2.33419537e-313, 2.75859453e-313, 3.18299369e-313,
       3.60739285e-313, 4.03179200e-313, 4.45619116e-313, 4.88059032e-313])
>>> c_binary2float.dtype
dtype('float64')
>>> c_binary2float = np.fromfile("b(空字符串表示二进制文件和整数).dat",dtype=np.float)
>>> c_binary2float
array([2.12199579e-314, 6.36598737e-314, 1.06099790e-313, 1.48539705e-313,
       1.90979621e-313, 2.33419537e-313, 2.75859453e-313, 3.18299369e-313,
       3.60739285e-313, 4.03179200e-313, 4.45619116e-313, 4.88059032e-313])
>>> c_binary2float.dtype # 这里数据读取有问题
dtype('float64')
>>> c_str = np.fromfile("b(逗号以及两位浮点数).dat",dtype=np.int,sep=",")
__main__:1: DeprecationWarning: string or file could not be read to its end due to unmatched data; this will raise a ValueError in the future.
>>> c_str,c_str.dtype
(array([0]), dtype('int32'))
>>> c_str = np.fromfile("b(逗号以及两位浮点数).dat",dtype=np.float,sep=",")
>>> c_str,c_str.dtype
(array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12.,
       13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23.]), dtype('float64'))
>>> c_str = np.fromfile("b(逗号和整数).dat",dtype=np.float,sep=",")
>>> c_str,c_str.dtype
(array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12.,
       13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23.]), dtype('float64'))
>>> c_str = np.fromfile("b(逗号和整数).dat",dtype=np.int,sep=",")
>>> c_str,c_str.dtype
(array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23]), dtype('int32'))
>>>
>>>

生成文件的内容截图展示:

在这里插入图片描述

NumPy自带的对高维数据存储和加载,特点是不需要保存高维数据的元数据,类型、维度等等,能够方便正确地还原出来,并且还可以用一个文件存储多个数组.

保存数据:

  • np.save(fname, array) 或np.savez(fname, array)
    • fname : 文件名,以.npy为扩展名,压缩扩展名为.npz
    • array : 数组变量

加载数据:

  • np.load(fname)
    • fname : 文件名,以.npy为扩展名,压缩扩展名为.npz

实验代码展示:

Microsoft Windows [版本 10.0.18363.1198]
(c) 2019 Microsoft Corporation。保留所有权利。

C:\Users\chenxuqi>cd C:\Users\chenxuqi\Desktop\numpy学习资料\Experiments4NumPy

C:\Users\chenxuqi\Desktop\numpy学习资料\Experiments4NumPy>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>> np.save("实验1a.npy",a)  # 两者等价
>>> # np.save("实验1a",a)  # 两者等价
...
>>> b = np.load("实验1a.npy")
>>> b
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>>
>>>

生成的文件,使用notepad++打开后的截图:
在这里插入图片描述实验2:
实验2参考链接: numpy.load

Microsoft Windows [版本 10.0.18363.1198]
(c) 2019 Microsoft Corporation。保留所有权利。

C:\Users\chenxuqi>cd C:\Users\chenxuqi\Desktop\numpy学习资料\Experiments4NumPy

C:\Users\chenxuqi\Desktop\numpy学习资料\Experiments4NumPy>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> ls2D = [[1, 2, 3], [4, 5, 6]]
>>> ls2D
[[1, 2, 3], [4, 5, 6]]
>>> ls1D = [1, 2]
>>> ls1D
[1, 2]
>>> a = np.array(ls2D)
>>> b = np.array(ls1D)
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> b
array([1, 2])
>>> np.savez('实验2a.npz', a=a, b=b)
>>> np.savez('实验2b', a=a, b=b)
>>> np.save('实验2c', a) # 假如a是一个很大的数组
>>> data_a = np.load('实验2a.npz')
>>> data_b = np.load('实验2b.npz')
>>> data_a
<numpy.lib.npyio.NpzFile object at 0x00000215925EF288>
>>> data_b
<numpy.lib.npyio.NpzFile object at 0x000002159262B588>
>>> data_a['a'],data_b['a']
(array([[1, 2, 3],
       [4, 5, 6]]), array([[1, 2, 3],
       [4, 5, 6]]))
>>> data_a['b'],data_b['b']
(array([1, 2]), array([1, 2]))
>>> data_a.close() # 一定要记得关闭
>>> data_b.close() # 一定要记得关闭
>>> # 假如文件:实验2c.npy是一个很大的文件,
... # 而且我们只需要用到其中的一小部分
... # 那么我们不需要完整地把整个文件读入内存
... # 只需要如下语句
...
>>> X = np.load('实验2c.npy', mmap_mode='r')
>>> X[1, :]
memmap([4, 5, 6])
>>>
>>>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值