问题描述
我有一个空白的 pdf 模板和一个包含一些数据的 Pandas 数据框。我想在 df 的一列中搜索特定模式,如果找到该模式,则从该行中获取数据并将其写入 pdf。我的搜索有效并且能够找到所有具有匹配项的行,并且我正在为具有匹配项的每一行生成一个新的 pdf 文件。但是,第二个、第三个等文件仍包含前几行的数据。我不确定为什么每次遍历循环时这些字符串都不会被覆盖。我还尝试在循环开始时将每个变量设置为 None ,但这没有帮助。
我的 df 有格式...
标题 | 类型 | H1 | H2 | H3 |
---|---|---|---|---|
s1 | 空白 | -- | -- | -- |
s2 | 261.1_1X | 1 | 2 | 3 |
s3 | 262.1_1X | 4 | 5 | 6 |
s4 | 空白 | -- | -- | -- |
我的代码能够找到模式(###.#_#X)并从这些行中获取数据,但第二个文件仍将包含第一行中的数据。
这是我的代码片段...
df = upload_spreadsheet(file_path,active_sheet_only=True)
text = ' '.join([str(x) for x in combine_dataframe(df)])
pattern = r'((\d+\.)(.*)(X))'
matches = text_search(text,pattern)
head1 = df.iloc[0,2]
head2 = df.iloc[0,3]
for i in matches: #This searches through the second column to match the samples
matchedRow = df[1].str.match(str(i))
rows = matchedRow[matchedRow==True]
val1 = df.iloc[rows.index[0],2]
val2 = df.iloc[rows.index[0],3]
newPDFname = str(df.iloc[rows.index[0],1])
pdf2 = FPDF()
pdf2.add_page()
pdf2.set_font('Arial','B',16)
xoffset = pdf2.x + 20
pdf2.x = xoffset
pdf2.setfillcolor = (0,255)
pdf2.multi_cell(0,10,str(head1)+' '+ str(val1),'L',fill = False)
pdf2.x = xoffset
pdf2.multi_cell(0,str(head2)+' '+ str(val2),fill = False)
pdf2.output('temp.pdf','F')
pdf2 = PdfFileReader('temp.pdf')
first_page1 = pdf1.getPage(0)
first_page2 = pdf2.getPage(0)
first_page1.mergePage(first_page2)
pdf_writer = PyPDF2.PdfFileWriter()
pdf_writer.addPage(first_page1)
with open(newPDFname+'.pdf',"wb") as filehandle_output:
pdf_writer.write(filehandle_output)
os.remove("temp.pdf")
解决方法
我不确定您是否正确选择了行。您的代码看起来很复杂。
您可以根据与此行匹配的字符串模式选择行:
foo = df[df['Type'].str.match(pattern)]