Python 2.7下基于条件提取Excel指定区域导入Pandas的问题
批量提取Excel指定行内容的实现方案(基于Python 2.7)
完全可以用你提到的索引定位逻辑实现需求,核心思路就是先找到包含"Item"的起始行、包含"Total"的结束行的索引,再通过df.loc截取目标范围的内容。以下是适配Python 2.7的具体实现:
核心逻辑说明
- 读取Excel时不预设表头,避免列名混乱导致读取错误;
- 遍历行定位起始索引(首个包含"Item"的行);
- 从起始行开始遍历,定位结束索引(首个包含"Total"的行);
- 用
df.loc[起始索引:结束索引-1]截取内容(跳过Total行),和你看到的Stack Overflow代码逻辑一致,都是通过索引值定位行范围。
代码实现
单个Excel文件处理函数
import pandas as pd def extract_target_data(file_path): # 读取Excel,不设置表头,用默认数字索引列名 df = pd.read_excel(file_path, header=None) start_idx = None end_idx = None # 定位包含"Item"的起始行 for idx, row in df.iterrows(): # 检查该行任意单元格是否包含"Item",空值转字符串避免报错 if any("Item" in str(cell) for cell in row): start_idx = idx break # 从起始行后定位包含"Total"的结束行 if start_idx is not None: for idx, row in df.loc[start_idx:].iterrows(): if any("Total" in str(cell) for cell in row): end_idx = idx break # 截取目标内容,跳过Total行;若要包含Total行则用start_idx:end_idx if start_idx is not None and end_idx is not None: target_df = df.loc[start_idx:end_idx-1].copy() # 用起始行内容作为表头,再移除原起始行 target_df.columns = target_df.iloc[0] target_df = target_df[1:] return target_df else: # 未找到目标行时返回空DataFrame return pd.DataFrame()
批量处理脚本
import os # 替换为你的Excel文件夹路径 folder_path = "你的Excel文件所在文件夹" all_extracted_data = [] for filename in os.listdir(folder_path): # 处理xls/xlsx格式文件 if filename.endswith((".xls", ".xlsx")): file_full_path = os.path.join(folder_path, filename) try: data_df = extract_target_data(file_full_path) if not data_df.empty: # 添加来源文件标记,方便溯源 data_df["来源文件"] = filename all_extracted_data.append(data_df) except Exception as e: print(f"处理文件{filename}失败: {str(e)}") # 合并所有提取的数据并保存 final_result = pd.concat(all_extracted_data, ignore_index=True) final_result.to_excel("提取结果汇总.xlsx", index=False)
注意事项
- Python 2.7需安装兼容版本的pandas,执行
pip install pandas==0.25.3(这是支持Python 2.7的最后一个pandas版本); - 若"Item"/"Total"大小写不固定,可改为
"item" in str(cell).lower()来忽略大小写判断; - 批量处理时的异常捕获能避免单个文件出错导致整个程序中断。
内容的提问来源于stack exchange,提问作者Cliff
相关产品推荐
相关产品推荐

