如何减少Python pandas对大体积Excel文件的读写耗时?
读写Excel性能优化方案
一、替换存储格式,从根本提升IO效率
Excel本身是带格式的封装存储,天生比扁平数据格式读写性能差,你的场景只有word、part两列数据,完全不需要Excel的格式特性,优先更换存储介质:
- 换成CSV格式:用
pd.read_csv()和pd.to_csv()读写,速度比Excel至少提升10倍,64万行数据读取可控制在1秒内,写入仅需数秒。如果后续必须要Excel格式输出,可单独做单次导出逻辑,不要用Excel作为日常迭代的中间存储介质。 - 换成Parquet格式:如果需要保留数据类型、多表等特性,可选择这种列式压缩存储格式,读写速度比CSV更快,磁盘占用也更小,安装
fastparquet或pyarrow依赖后,调用pd.read_parquet()、pd.to_parquet()即可使用。
二、如果必须保留Excel格式,优化读写参数
读取优化
- 仅加载需要的列:你最终只用到
word和part两列,读取时指定usecols参数,避免加载无用列:
dictionary = pd.read_excel('./first_dictionary.xlsx', usecols=['word', 'part'])
- 更换高性能读取引擎:默认xlrd引擎对大文件适配差,换成openpyxl并开启只读模式:
dictionary = pd.read_excel('./first_dictionary.xlsx', usecols=['word', 'part'], engine='openpyxl', read_only=True)
写入优化
- 开启大文件写入优化:用openpyxl引擎,开启zip64适配大文件:
dictionary.to_excel('first_dictionary.xlsx', sheet_name = "Sheet_1", index=None, engine='openpyxl', use_zip64=True)
- 跳过全量读写直接追加:你的场景只是追加新数据,不需要读取全量再回写,用openpyxl直接定位到表格最后一行追加写入即可,性能提升最多:
from openpyxl import load_workbook # 仅加载工作簿结构,不读取全量数据 wb = load_workbook('first_dictionary.xlsx', read_only=False) ws = wb['Sheet_1'] # 定位到最后一行的下一行 start_row = ws.max_row + 1 # 逐行写入新数据 for idx, row in new_word_list.iterrows(): ws.cell(row=start_row+idx, column=1, value=row['word']) ws.cell(row=start_row+idx, column=2, value=row['part']) wb.save('first_dictionary.xlsx')
三、现有代码冗余点优化
- 新增去重逻辑:当前代码多次调用会出现数据重复,建议concat后添加
dictionary = dictionary.drop_duplicates(subset=['word'], keep='last')。 - 优化CSV写入逻辑:不需要逐行迭代写文件,用向量化操作生成内容后一次性写入,同时用
with语句管理文件句柄更安全:
new_word_pt['custom_line'] = new_word_pt['word'] + ',*,*,*,' + new_word_pt['part'] + ',*,T,' + new_word_pt['word'] + ',*,*,*,*,*\n' with open(user_dicpath, 'a', encoding="UTF-8") as f: f.writelines(new_word_pt['custom_line'].tolist())
- 删除冗余操作:代码中的
reset_index是无效操作,不影响最终取两列输出,可直接删掉。
内容的提问来源于stack exchange,提问作者김만기
相关产品推荐
相关产品推荐

