numpy数组之存取文件的实现示例
Python  /  管理员 发布于 5年前   196
将 numpy 数组存入文件,有多种文件类型可供选择,对应地就有不同的方法来读写。
下面我将介绍读写 numpy 的三类文件:
通过 numpy 读写 txt 或 csv 文件
import numpy as npa = np.array(range(20)).reshape((4, 5))print(a)# 后缀改为 .txt 一样filename = 'data/a.csv'# 写文件np.savetxt(filename, a, fmt='%d', delimiter=',')# 读文件b = np.loadtxt(filename, dtype=np.int32, delimiter=',')print(b)
缺点:
通过 numpy 读写 npy 或 npz 文件
读写 npy 文件
import numpy as npa = np.array(range(20)).reshape((2, 2, 5))print(a)filename = 'data/a.npy'# 写文件np.save(filename, a)# 读文件b = np.load(filename)print(b)print(b.shape)
优点:
缺点:
读写 npz 文件
import numpy as npa = np.array(range(20)).reshape((2, 2, 5))b = np.array(range(20, 44)).reshape(2, 3 ,4)print('a:\n', a)print('b:\n', b)filename = 'data/a.npz'# 写文件, 如果不指定key,那么默认key为'arr_0'、'arr_1',一直排下去。np.savez(filename, a, b=b)# 读文件c = np.load(filename)print('keys of NpzFile c:\n', c.keys())print("c['arr_0']:\n", c['arr_0'])print("c['b']:\n", c['b'])
优点:
缺点:
通过 h5py 读写 hdf5 文件
优点:
简单读取
import numpy as npimport h5pya = np.array(range(20)).reshape((2, 2, 5))b = np.array(range(20)).reshape((1, 4, 5))print(a)print(b)filename = 'data/data.h5'# 写文件h5f = h5py.File(filename, 'w')h5f.create_dataset('a', data=a)h5f.create_dataset('b', data=b)h5f.close()# 读文件h5f = h5py.File(filename, 'r')print(type(h5f))# 通过切片得到numpy数组print(h5f['a'][:])print(h5f['b'][:])h5f.close()
通过切片赋值
import numpy as npimport h5pya = np.array(range(20)).reshape((2, 2, 5))print(a)filename = 'data/a.h5'# 写文件h5f = h5py.File(filename, 'w')# 当数组a太大,需要切片进行操作时,可以不直接对h5f['a']进行初始化;# 当之后不需要改变h5f['a']的shape时,可以省略maxshape参数h5f.create_dataset('a', shape=(2, 2, 5), maxshape=(None, 2, 5), dtype=np.int32, compression='gzip')for i in range(2): # 采用切片的形式赋值 h5f['a'][i] = a[i]h5f.close()# 读文件h5f = h5py.File(filename, 'r')print(type(h5f))print(h5f['a'])# 通过切片得到numpy数组print(h5f['a'][:])
同一个 hdf5 文件可以创建多个 dataset,读取的时候按照 key 来即可。
总结
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号