You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Camelot提取PDF表格后,如何遍历DataFrame遇空单元格拼接字符串?

处理Camelot提取PDF表格的合并单元格问题

解决方案思路

遍历第一列单元格,维护临时列表收集连续非空内容,遇到空单元格时,将列表内容以空格拼接后赋值给该段第一个非空单元格,同时清空该段其他单元格的内容;遍历结束后处理末尾未遇到空单元格的连续非空段。

代码实现

假设你已通过Camelot提取得到Pandas DataFrame格式的表格df,第一列名为col1:

import pandas as pd

# 初始化临时存储和起始索引
temp_items = []
first_non_empty_idx = None

for idx, cell_value in df['col1'].items():
    # 判断单元格是否为空(适配NaN、空字符串两种情况)
    is_empty = pd.isna(cell_value) or (isinstance(cell_value, str) and cell_value.strip() == '')
    
    if not is_empty:
        if first_non_empty_idx is None:
            first_non_empty_idx = idx
        temp_items.append(str(cell_value).strip())
    else:
        # 当收集到多个非空内容时执行拼接
        if first_non_empty_idx is not None and len(temp_items) > 1:
            # 拼接内容到第一个非空单元格
            df.at[first_non_empty_idx, 'col1'] = ' '.join(temp_items)
            # 清空该段后续的非空单元格
            for i in range(first_non_empty_idx + 1, idx):
                df.at[i, 'col1'] = ''
        # 重置临时变量
        temp_items = []
        first_non_empty_idx = None

# 处理遍历结束后剩余的连续非空段
if first_non_empty_idx is not None and len(temp_items) > 1:
    df.at[first_non_empty_idx, 'col1'] = ' '.join(temp_items)
    # 清空后续相关单元格
    for i in range(first_non_empty_idx + 1, df.shape[0]):
        current_val = df.at[i, 'col1']
        if not pd.isna(current_val) and current_val.strip() != '':
            df.at[i, 'col1'] = ''
        else:
            break

关键说明

  • 空值判断逻辑:同时适配Camelot提取可能产生的NaN和空字符串,可根据实际提取结果调整。
  • 临时变量作用:temp_items存储连续非空内容,first_non_empty_idx标记该段第一个非空单元格的位置。
  • 边界处理:额外处理遍历结束后未遇到空单元格的连续段,避免内容遗漏。

内容的提问来源于stack exchange,提问作者NoExpert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 10:33:30