我们知道Excel有一个match函数,可以做数据匹配。
比如要根据人名获取成绩

利用Python实现Excel的文件间的数据匹配功能

而参考表sheet1的内容如下:

利用Python实现Excel的文件间的数据匹配功能

要根据sheet1匹配每人的成绩,用Excel是这么写

index(Sheet1!B:B,MATCH(A2,Sheet1!A:A,0))

意思就是获取sheet1的B列的内容,根据我的A列匹配sheet1的A列的内容

但是如何用python实现这一点呢,我写了一个函数,非常好用,分享给大家。
这个函数考虑到了匹配多个字段,多个sheet。

import pandas as pd
def match(file,sheetnames,reffile,refsheet,targetsegs,matchseg)  #文件名 sheet列表 参考文件名 参考sheet 目标字段列表 参考字段
	alldata=pd.read_excel(file,None)
	refdata=pd.read_excel(reffile,refsheet)
	#获取映射字典
	maps={}
	for i in refdata.index:
		MatchSeg=refdata.loc[i,matchseg]
		maps[MatchSeg]={}
		for seg in targetsegs:
			maps[MatchSeg][seg]=refdata.loc[i,seg]
	#匹配数据
	for sheet in sheetnames:
		if(isinstance(sheet,int)):
			sheet=list(alldata.keys())[sheet]

		data=alldata[sheet].fillna('-')
		for i in data.index:
			MatchSeg=data.loc[i,matchseg]
			for seg in targetsegs:
				try:
					data.loc[i,seg]=map[MatchSeg][seg]
				except Exception as e:
					pass

		alldata[sheet]=data
	#导出
	with pd.ExcelWriter(file) as writer:
		for sheet in alldata.keys():
			alldata[sheet].to_excel(writer,sheet,index=False)
			
match('要匹配的表.xlsx',[0,1],'参考表.xlsx','参考页',['要匹配的字段1,字段2'],'参考字段')

总结

标签:
Python实现Excel的文件间的数据匹配,python,excel,数据匹配

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。