numpy-写入与读取

这篇博客介绍了numpy库中用于二进制文件和文本文件读写的函数,包括save()、savez()、load()、savetxt()、loadtxt()、genfromtxt()等。此外,还详细阐述了文本格式的选项,如设置浮点精度、概略显示阈值和换行符等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二进制文件

save(),savez()和load()函数以及numpy专用的二进制类型(npy,npz)保存和读取数据,这三个函数会自动处理ndim、dtype、shape等信息,使用它们读写数组非常方便。

npy:以二进制的方式存储文件,在二进制文件第一行以文件形式保存了数据的元信息,可以用二进制工具查看内容。

npz格式:以压缩打包的方式存储文件,可以用压缩软件解压。

numpy.save(file,arr,allow_pickle = True,fix_imports =True) 

numpy.load(file,mmap_mode = None,allow_pickle = False,fix_imports = True,encoding = "ASCII")

import numpy as np 
outfile = r".\test.npy"
np.random.seed(20200619)
x = np.random.uniform(0,1,[3,5])
np.save(outfile,x)
y = np.load(outfile)
print(y)

[[0.01123594 0.66790705 0.50212171 0.7230908  0.61668256]
 [0.00668332 0.1234096  0.96092409 0.67925305 0.38596837]
 [0.72342998 0.26258324 0.24318845 0.98795012 0.77370715]]

savez()第一个参数是文件名,其后的参数都是需要保存的数组。

savez()输出的是一个压缩文件(扩展名npz),其中每个文件都是一个save()保存的npy文件,文件名对应数组名。load()自动识别npz文件,并且返回一个类似字典的对象,可以通过数组名作为关键字获取数组的内容。

将多个数组保存到一个文件,可以用numpy.savez()函数

import numpy as np 
outfile = r".\test.npz"
x = np.linspace(0,np.pi,5)
y = np.sin(x)
z = np.cos(x)
np.savez(outfile,x,y,z_d = z)
data = np.load(outfile)
np.set_printoptions(suppress = True)
print(data.files)
print(data["z_d"])
print(data["arr_0"])
print(data["arr_1"])

文本文件

savetxt(),loadtxt()和genfromtxt()函数用于存储和读取文本文件,genfromtxt()比loadtxt()更加强大,可对缺失数据进行处理

  • numpy.savetxt(fname,X,fmt="%.18e",delimiter = " ",newline = "\n",header = " ",footer = " ",comments = "#",encoding = None)

fname:文件路径

X:存入的文件数组

fmt:每个元素的字符串格式,默认%.18e

delimiter :分割字符串,,默认空格分割

  • numpy.loadtxt(fname,dtype = fload,comments = "#",deliniter = None,converters = None ,skiprows = 0,usecols = None ,unpack = False,ndmin = 0.encoding = "btypes",max_rows = None)

fname :文件路径

dtype:数据类型

comments :字符串或者字符串组成的列表,默认为#

skiprows:跳过多少行,一般跳过表头

usecols:元组

unpack:当加载多列数据时是否需要将数据列进行解耦赋值给不同的变量

写入或读出TXT文件


import numpy as np 
outfile = r".\test.txt"
x = np.arange(0,10).reshape(2,-1)
np.savetxt(outfile,x)
y = np.loadtxt(outfile)
print(y)

写入和读取CSV文件


import numpy as np 

outfile = r".\test.csv"
x = np.arange(0,10,0.5).reshape(4,-1)
np.savetxt(outfile,x,fmt = "%.3f",delimiter = ",")
y = np.loadtxt(outfile,delimiter = ",")
print(y)

genfromtxt()是面向结构数组和缺失数据处理的

numpy.genfromtxt(fname,dtype = float,comments = "#",delimiter = None,skip_header = 0,skip_footer = 0,converters =None,missing_valuse =None,filling_values=None,usecols = None ,names = None,excludelist = None,deletechars = "".join(sorted(NameValidator.defaultdeletechars)), replace_space='_', autostrip=False, case_sensitive=True, defaultfmt="f%i", unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding='bytes')

import numpy as np

outfile = r'.\data.csv'
x = np.loadtxt(outfile, delimiter=',', skiprows=1)
print(x)
x = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2))
print(x)
val1, val2 = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2), unpack=True)
print(val1)  # [123. 110. 164.]
print(val2)
import numpy as np

outfile = r'.\data.csv'
x = np.genfromtxt(outfile, delimiter=',', names=True)
print(x)
print(type(x)) 
print(x.dtype)
print(x['id'])  
print(x['value1'])  
print(x['value2']) 
print(x['value3']) 

 

import numpy as np

outfile = r'.\data1.csv'
x = np.genfromtxt(outfile, delimiter=',', names=True)

print(x)

print(type(x))  

print(x.dtype)
print(x['id'])  
print(x['value1'])  
print(x['value2'])  
print(x['value3'])  

文本格式选项

  • numpy.set_printoptions(precision=None,threshold=None, edgeitems=None,linewidth=None, suppress=None, nanstr=None, infstr=None,formatter=None, sign=None, floatmode=None, **kwarg)

precision:设置浮点精度,控制输出的小数点个数,默认是8。

threshold:概略显示,超过该值则以“…”的形式来表示,默认是1000。

linewidth:用于确定每行多少字符数后插入换行符,默认为75。

suppress:当suppress=True,表示小数不需要以科学计数法的形式输出,默认是False。

nanstr:浮点非数字的字符串表示形式,默认nan。 infstr:浮点无穷大的字符串表示形式,默认inf。

import numpy as np

np.set_printoptions(precision=4)
x = np.array([1.123456789])
print(x)  

np.set_printoptions(threshold=20)
x = np.arange(50)
print(x)  

np.set_printoptions(threshold=np.iinfo(np.int).max)
print(x)

eps = np.finfo(float).eps
x = np.arange(4.)
x = x ** 2 - (x + eps) ** 2
print(x)  

np.set_printoptions(suppress=True)
print(x)  

x = np.linspace(0, 10, 10)
print(x)

np.set_printoptions(precision=2, suppress=True, threshold=5)
print(x)  
  • numpy.get_printoptions() Return the current print options.
    import numpy as np
    
    x = np.get_printoptions()
    print(x)

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值