在數(shù)據(jù)處理與分析中,經(jīng)常需要比較來自不同來源的數(shù)據(jù)集,特別是在處理涉及多個Excel工作簿和工作表的場景時。Python的Pandas庫提供了強大的工具,可以幫助我們高效地完成這一任務。下面,我們將一步步引導你如何使用Python對比兩個Excel文件中多個Sheet的數(shù)據(jù)。
確保你的Python環(huán)境中已安裝pandas和openpyxl。如果沒有安裝,可以通過以下命令安裝:
pip install pandas openpyxl
使用pandas.ExcelFile或pandas.read_excel直接讀取多個Sheet的數(shù)據(jù)。
import pandas as pd# 讀取第一個Excel文件的所有Sheetxlsx1 = pd.ExcelFile('file1.xlsx')sheets1 = {sheet_name: xlsx1.parse(sheet_name) for sheet_name in xlsx1.sheet_names}# 讀取第二個Excel文件的所有Sheetxlsx2 = pd.ExcelFile('file2.xlsx')sheets2 = {sheet_name: xlsx2.parse(sheet_name) for sheet_name in xlsx2.sheet_names}
對比兩個Excel文件中相同名稱的Sheet。我們可以逐個Sheet進行對比,尋找不一致的數(shù)據(jù)行。
# 創(chuàng)建一個空的字典來存儲對比結(jié)果comparison_results = {}for sheet_name in sheets1.keys(): if sheet_name in sheets2: # 如果兩個文件都有相同的Sheet,則進行對比 df1 = sheets1[sheet_name] df2 = sheets2[sheet_name] # 比較兩個DataFrame comparison = df1.merge(df2, how='outer', indicator=True) comparison_results[sheet_name] = comparison[comparison['_merge'] != 'both']
上述對比會返回一個新DataFrame,其中包含標記為left_only或right_only的行,表示只在左側(cè)或右側(cè)數(shù)據(jù)集中存在。此外,還可以通過left和right后綴訪問原始數(shù)據(jù)列。
# 分析差異for sheet_name, result in comparison_results.items(): if not result.empty: print(f"Differences found in '{sheet_name}':") print(result)
將對比結(jié)果保存到新的Excel文件中,便于后續(xù)分析或報告。
with pd.ExcelWriter('comparison_results.xlsx') as writer: for sheet_name, result in comparison_results.items(): if not result.empty: result.to_excel(writer, sheet_name=sheet_name, index=False)
完整代碼示例
下面是將上述步驟整合在一起的完整代碼示例:
import pandas as pd# 讀取Excel文件xlsx1 = pd.ExcelFile('file1.xlsx')xlsx2 = pd.ExcelFile('file2.xlsx')# 讀取所有Sheetsheets1 = {sheet_name: xlsx1.parse(sheet_name) for sheet_name in xlsx1.sheet_names}sheets2 = {sheet_name: xlsx2.parse(sheet_name) for sheet_name in xlsx2.sheet_names}# 創(chuàng)建一個空的字典來存儲對比結(jié)果comparison_results = {}# 對比數(shù)據(jù)for sheet_name in sheets1.keys(): if sheet_name in sheets2: df1 = sheets1[sheet_name] df2 = sheets2[sheet_name] comparison = df1.merge(df2, how='outer', indicator=True) comparison_results[sheet_name] = comparison[comparison['_merge'] != 'both']# 保存對比結(jié)果with pd.ExcelWriter('comparison_results.xlsx') as writer: for sheet_name, result in comparison_results.items(): if not result.empty: result.to_excel(writer, sheet_name=sheet_name, index=False)
通過上述步驟,你可以有效地對比兩個Excel文件中多個Sheet的數(shù)據(jù),找出差異并保存結(jié)果。這種方法特別適用于財務審計、數(shù)據(jù)清洗或任何需要跨數(shù)據(jù)集一致性檢查的場景。
希望這篇指南能夠幫助你在Python中處理復雜的Excel數(shù)據(jù)對比任務。
本文鏈接:http://www.tebozhan.com/showinfo-26-101107-0.htmlPython兩個Excel多Sheet數(shù)據(jù)對比
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 智啟萬象|2024 Google 谷歌開發(fā)者大會邀你報名「暢享家」
下一篇: 一圖看懂八大擴展系統(tǒng)的方法