pandas批量读取多Excel时跳过不固定无效行与页脚并合并为DataFrame
不规则Excel批量自动清洗实现方案
核心适配逻辑
全程不需要逐文件手动配置跳过行数、页脚截断位置,通过通用特征自动识别有效内容边界:
- 前置无效内容自动跳过:逐行扫描全表原始内容,定位符合「非空单元格数≥3、无大段报告类长文本」特征的第一行作为正式表头,该行以上的报告内容全部自动丢弃
- 尾部无效页脚自动过滤:从表头下一行开始遍历,当连续2行的非空单元格数量不足表头非空数的30%时,判定为页脚起始位置,截断后续所有无效内容
嵌入现有代码的完整实现
先封装通用的不规则Excel读取函数,替换原有固定参数读取逻辑:
import os import re import pandas as pd def read_irregular_excel(file_path): # 全量读取Excel所有单元格内容,不预设表头 raw_df = pd.read_excel(file_path, header=None, dtype=str).fillna("") # 计算每行非空单元格数量 row_nonempty = (raw_df != "").sum(axis=1) # 定位有效表头候选行 candidate_rows = [] for row_idx, row in raw_df.iterrows(): nonempty_cells = row[row != ""] if len(nonempty_cells) < 3: continue # 排除大段报告文本的行(单格内容超50字的占比超10%即判定为报告内容) long_text_ratio = (nonempty_cells.str.len() > 50).sum() / len(nonempty_cells) if long_text_ratio < 0.1: candidate_rows.append(row_idx) if not candidate_rows: return None # 取第一个符合特征的行作为正式表头 header_idx = candidate_rows[0] header = raw_df.iloc[header_idx].values data_region = raw_df.iloc[header_idx+1:] header_nonempty_cnt = row_nonempty.iloc[header_idx] # 定位页脚起始位置 consecutive_short = 0 footer_pos = len(data_region) for pos, (row_idx, _) in enumerate(data_region.iterrows()): row_cnt = row_nonempty.iloc[row_idx] if row_cnt < header_nonempty_cnt * 0.3: consecutive_short +=1 if consecutive_short >=2: footer_pos = pos break else: consecutive_short = 0 # 组装干净的数据集 clean_df = data_region.iloc[:footer_pos].copy() clean_df.columns = header # 清理全空的列和行 clean_df = clean_df.dropna(axis=1, how="all") clean_df = clean_df[~(clean_df == "").all(axis=1)] return clean_df # 原有遍历逻辑替换读取部分 cd = os.path.dirname(os.path.abspath("D:\project")) i = 0 dfList = [] for root, dirs, files in os.walk(cd): for fname in files: if re.match("^.*.xlsx$", fname): file_full_path = os.path.join(root, fname) # 替换原有固定参数读取的调用 data = read_irregular_excel(file_full_path) if data is not None: dfList.append(data) i += 1 df = pd.concat(dfList, ignore_index=True)
可调整的优化方向
- 如果业务侧有固定的列名规则(比如固定包含「订单编号」「交易日期」等字段),可以在候选表头判断逻辑中增加「行内容包含所有指定列名」的校验,进一步提升识别准确率
- 如果文件存在多工作表结构,可以先遍历所有工作表,对每个工作表应用上述识别逻辑,选中包含有效表头的工作表读取,避免读错表
- 针对固定格式的页脚文本(比如固定落款“本报告生成于X年X月X日”),可以在页脚判断逻辑中增加文本匹配规则,遇到匹配内容直接截断
内容的提问来源于stack exchange,提问作者Michell
相关产品推荐
相关产品推荐

