有人可以建议如何有效地从 PDF 中提取此表格(上面的链接)吗?我主要使用 tabula,因为它似乎是识别和提取表格的最佳 Python 库。
我想提取到具有单元结构的数据框中,如下图所示:
我愿意用上面/下面的子标题来填充 nan。
该文件(“doc”)是 Marshalls plc 的 2023 年年度报告(实际文件页码 = 92),可通过以下链接获取: https://www.marshalls.co.uk/investor/results-reports-and-presentations
我想出了以下代码来提取每行的元素,但它合并了一些元素,例如第 1 行中的第 5 个元素(从零开始)实际上应该是两个元素(“MIP A”和“MIP B”)而不是一个(“MIP A MIP B”)。正如您所看到的,每行应该有 19 个元素,包括第一列中的高管姓名。现在,代码输出中每个元素只有 10 个元素。
import tabula
dfs = tabula.read_pdf(doc, pages='94') # multiple_tables=True
dfs
row_number = 1 # Row number you want to access (zero-based)
# Iterate over each DataFrame in the list and access a specified row of actual data
for i, df in enumerate(dfs):
if not df.empty: # Ensure DataFrame is not empty
if len(df) > row_number: # Check if DataFrame has enough rows
specified_row = df.iloc[row_number] # Access the specified row of data
print(f"Data from row {row_number + 1} in Table {i+1}:")
print(specified_row.values) # Print only the values from the specified row
print(f"\nNumber of elements in row {row_number + 1} of Table {i+1}: {len(specified_row.values)}")
else:
print(f"Table {i+1} does not contain row {row_number + 1}.")
else:
print(f"Table {i+1} is empty.")
我应该补充一点,我需要能够应用于其他表格并类似地检测单元格之间的划分,因此拥有如下所示的具体引用是没有好处的:
def split_specific_items(row_values):
updated_values = []
for item in row_values:
if item == 'MIP A MIP B':
updated_values.extend(['MIP A', 'MIP B'])
else:
updated_values.append(item)
return updated_values