如何提升Pandas read_excel速度?批量处理2250个Excel文件
高效批量处理大Excel文件的优化方案
1. 先校验列数,避免无效读取
不要直接读取整个文件,先仅读取首行表头校验列数是否为88,不符合的直接跳过,减少不必要的IO操作:
import pandas as pd def check_columns(file_path): # 仅读取首行表头,获取列数 header_df = pd.read_excel(file_path, nrows=0) return len(header_df.columns) == 88
2. 用轻量库直接读取目标行,跳过冗余数据
放弃pandas全量读取,改用openpyxl(针对.xlsx)或xlrd(针对.xls)直接遍历行,只收集Agent列非空的行,读到目标数量后立即停止:
from openpyxl import load_workbook def extract_target_rows(file_path): wb = load_workbook(file_path, read_only=True) # 只读模式大幅提升速度 ws = wb.active # 先找到Agent列的索引(假设表头在第1行) agent_col_idx = None for idx, cell in enumerate(ws[1]): if cell.value == "Agent": agent_col_idx = idx break if not agent_col_idx: return None target_rows = [] # 从第2行开始遍历,跳过隐藏行+收集Agent非空行 for row in ws.iter_rows(min_row=2): if row.hidden: # 跳过隐藏的重复行 continue agent_value = row[agent_col_idx].value if agent_value is not None and agent_value != "": target_rows.append([cell.value for cell in row]) # 达到目标行数范围可提前终止 if len(target_rows) >= 50: break wb.close() return target_rows
3. 并行处理加速批量任务
2250个文件单线程循环太慢,用多进程并行处理(CPU密集型任务优先用进程):
from concurrent.futures import ProcessPoolExecutor import os file_list = [f for f in os.listdir("your_excel_dir") if f.endswith((".xlsx", ".xls"))] def process_single_file(file_name): file_path = os.path.join("your_excel_dir", file_name) if not check_columns(file_path): return (file_name, "列数不符合") rows = extract_target_rows(file_path) return (file_name, rows) # 按CPU核心数设置进程数 with ProcessPoolExecutor(max_workers=os.cpu_count()) as executor: results = list(executor.map(process_single_file, file_list)) # 后续可将结果保存到统一文件 import pandas as pd all_data = [] for file_name, rows in results: if isinstance(rows, list) and rows: # 复用表头信息 header = pd.read_excel(os.path.join("your_excel_dir", file_name), nrows=0).columns df = pd.DataFrame(rows, columns=header) all_data.append(df) final_df = pd.concat(all_data, ignore_index=True) final_df.to_excel("merged_result.xlsx", index=False)
额外优化点
- 确保安装对应库:
pip install openpyxl pandas - 对于.xls格式,替换为
xlrd(注意xlrd 2.0+不支持.xlsx,需安装xlrd<2.0) - 如果文件分散在子目录,用
os.walk递归遍历所有Excel文件
内容的提问来源于stack exchange,提问作者Mrbowtie
相关产品推荐
相关产品推荐

