利用Python實(shí)現(xiàn)Excel的文件間的數(shù)據(jù)匹配功能
我們知道Excel有一個(gè)match函數(shù),可以做數(shù)據(jù)匹配。比如要根據(jù)人名獲取成績(jī)
而參考表sheet1的內(nèi)容如下:
要根據(jù)sheet1匹配每人的成績(jī),用Excel是這么寫(xiě)
index(Sheet1!B:B,MATCH(A2,Sheet1!A:A,0))
意思就是獲取sheet1的B列的內(nèi)容,根據(jù)我的A列匹配sheet1的A列的內(nèi)容
但是如何用python實(shí)現(xiàn)這一點(diǎn)呢,我寫(xiě)了一個(gè)函數(shù),非常好用,分享給大家。這個(gè)函數(shù)考慮到了匹配多個(gè)字段,多個(gè)sheet。
import pandas as pddef match(file,sheetnames,reffile,refsheet,targetsegs,matchseg) #文件名 sheet列表 參考文件名 參考sheet 目標(biāo)字段列表 參考字段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]#匹配數(shù)據(jù)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:passalldata[sheet]=data#導(dǎo)出with pd.ExcelWriter(file) as writer:for sheet in alldata.keys():alldata[sheet].to_excel(writer,sheet,index=False)match(’要匹配的表.xlsx’,[0,1],’參考表.xlsx’,’參考頁(yè)’,[’要匹配的字段1,字段2’],’參考字段’)
總結(jié)
到此這篇關(guān)于利用Python實(shí)現(xiàn)Excel的文件間的數(shù)據(jù)匹配功能的文章就介紹到這了,更多相關(guān)Python實(shí)現(xiàn)Excel的文件間的數(shù)據(jù)匹配內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. asp文件如何打開(kāi)2. Spring依賴(lài)注入的三種方式實(shí)例詳解3. JSP出現(xiàn)中文亂碼問(wèn)題解決方法詳解4. 怎樣打開(kāi)XML文件?xml文件如何打開(kāi)?5. ASP基礎(chǔ)入門(mén)第二篇(ASP基礎(chǔ)知識(shí))6. ASP.NET MVC限制同一個(gè)IP地址單位時(shí)間間隔內(nèi)的請(qǐng)求次數(shù)7. ASP和PHP文件操作速度的對(duì)比8. ASP.NET MVC實(shí)現(xiàn)登錄后跳轉(zhuǎn)到原界面9. jsp實(shí)現(xiàn)局部刷新頁(yè)面、異步加載頁(yè)面的方法10. jsp實(shí)現(xiàn)簡(jiǎn)單用戶(hù)7天內(nèi)免登錄
