[英]Using python how to take input search string from one excel sheet column and search in other excel on a specific column?
例如,從文件 1 的 col A 中獲取輸入字符串 _TXT,然后在文件 2 的 col X 中搜索。如果任何行包含 _TXT,則對於該特定行,將 col B 值與文件 1 和文件 2 中的 col Y 值進行比較。
如果 B 列和 Y 列值匹配,則不采取任何操作。 如果它們不匹配,則使用與文件 1 中的 col B 相同的值更新文件 2 中的 col Y
一個簡單的(雖然可能不是最有效的)方法是遵循這個算法:
Pandas 提供 function 來讀取 excel 文件 ( read_excel )。 鏈接中記錄了很多選項:我認為對您有用的選項是:
function 將您的 pandas dataframe 寫回 excel 是 class DataFrame(完整文檔在這里)調用 to_excel 的方法。 有用的選項包括:
您的最終代碼可能如下所示:
from pandas import *
# read both excel files ; assume only one sheet in file to modify
# taking only useful columns in reference file according to your example
dfIn = read_excel("path/to/refFile.xlsx", usecols="A:B")
dfOut = read_excel("path/to/outFile.xlsx", usecols=None, sheet_name="data_sheet")
for index, rowIn in dfIn.iterrows():
inputString = rowIn['colA']
for index, rowOut in dfOut.iterrows():
# using python string endswith as matching rule
# replace with anything that suits your needs
if rowOut['colX'].endswith(inputString):
rowOut['colY'] = rowIn['colB']
# write dfOut to disk
with ExcelWriter("path/to/outFile.xlsx", mode="a", if_sheet_exists="replace") as writer:
dfOut.to_excel(writer, sheet_name="data_sheet", index=False)
誠然,pandas 文檔警告不要修改您正在迭代的內容(因為 iterrows 可能返回數據的副本而不是視圖,然后更改副本將無效)。 由於您在此處使用字符串,因此修改將起作用。
根據您的 excel 引擎及其版本(它適用於 python 3.8.10 和 openpyxl 3.0.9,但對於 OP 失敗)替換工作表可能會失敗。 如果是這種情況, 這個相關問題建議完全刪除舊表並制作新表,如下所示:
with ExcelWriter('/path/to/file.xlsx',engine = "openpyxl", mode='a') as writer:
workBook = writer.book
# data_sheet exists for sure, since we read data from it at beginning of script
workBook.remove(['data_sheet'])
df.to_excel(writer, sheet_name='data_sheet', index=False)
writer.save()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.