利用Python實現(xiàn)Excel的文件間的數(shù)據(jù)匹配功能
我們知道Excel有一個match函數(shù),可以做數(shù)據(jù)匹配。
比如要根據(jù)人名獲取成績
而參考表sheet1的內(nèi)容如下:
要根據(jù)sheet1匹配每人的成績,用Excel是這么寫
index(Sheet1!B:B,MATCH(A2,Sheet1!A:A,0))
意思就是獲取sheet1的B列的內(nèi)容,根據(jù)我的A列匹配sheet1的A列的內(nèi)容
但是如何用python實現(xiàn)這一點呢,我寫了一個函數(shù),非常好用,分享給大家。
這個函數(shù)考慮到了匹配多個字段,多個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] #匹配數(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: 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實現(xiàn)Excel的文件間的數(shù)據(jù)匹配功能的文章就介紹到這了,更多相關Python實現(xiàn)Excel的文件間的數(shù)據(jù)匹配內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
anaconda的安裝和配置環(huán)境及導入pycharm的方法
這篇文章主要介紹了anaconda的安裝和配置環(huán)境及導入pycharm的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03Python數(shù)據(jù)可視化之Matplotlib初級使用指南
Matplotlib是Python中最常用的數(shù)據(jù)可視化庫之一,它提供了豐富的圖表類型和靈活的自定義選項,能幫助我們以更直觀的方式理解數(shù)據(jù),本文將對Matplotlib的基本功能進行介紹,包括如何創(chuàng)建和自定義圖表等2023-07-07使用Python操作MySql數(shù)據(jù)庫和MsSql數(shù)據(jù)庫
這篇文章介紹了使用Python操作MySql數(shù)據(jù)庫和MsSql數(shù)據(jù)庫的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05