【Python数据分析系列】一文教你分块多线程处理超大的excel表格(案例+源码)
·
这是我的第456篇原创文章。
一、引言
场景:我需要处理一个很大的excel文件,比如上万行,需要对其中某一列做解析处理,将解析出的结果另存为新的字段保存。由于数据敏感,结果就不展示了,大家学习一下思路,适用于任何处理大excel表格的场景。
二、实现过程
2.1 读取excel文件
核心代码:
df = pd.read_excel('近一个月中标数据标签.xlsx')
2.2 参数配置
核心代码:
detail_col = '近一个月中标详情'
chunk_size = 1000 # 每块处理多少行
max_workers = 32 # 线程数
2.3 初始化结果列表
核心代码:
total_rows = len(df)
results = [None] * total_rows
2.4 构建索引列表
核心代码:
all_indices = list(df.index)
2.5 执行多线程分块处理
核心代码:
with ThreadPoolExecutor(max_workers=max_workers) as executor:
num_chunks == math.ceil(total_rows / chunk_size)
chunk_indices_list = [all_indices[i * chunk_size: (i+1) * chunk_size] for i in range(num_chunks)]
future_to_chunk = {
executor.submit(process_chunk, chunk, df, detail_col): chunk
for chunk in chunk_indices_list
}
for future in tqdm(as_completed(future_to_chunk), total=len(future_to_chunk), desc="分块并行提取")
try:
for idx, vals in future.result():
results[idx] = vals
except Exception as e:
print(f"warning: chunk processing error: {e}")
定义分块处理函数:处理一个chunk的行
def process_chunk(chunk_indices, df, detail_col):
chunk_results = []
for idx in chunk_indices:
json_str = df.loc[idx, detail_col]
if pd.isna(json_str):
chunk_results.append([None] * 5)
else:
chunk_results.append(extract_first_bid_info(json_str))
return list(zip(chunk_indices, chunk_results))
定义解析函数
def extract_first_bid_info(json_str):
try:
data = json.loads(json_str)
first_list = data.get("中标信息", [])
inner_list = first_list[0]['中标信息']
first_item = inner_list[0]
title = first_item.get("信息标题")
date = first_item.get('发布日期')
amount = first_item.get('中标金额')
region = first_item.get('地区')
bidder = first_item.get('招标方')
return [title, data, amount, region, bidder]
except Exception:
return [None] * 5
2.6 整合结果
核心代码:
new_cols = ['信息标题', '发布日期', '中标金额', '地区', '招标方']
extract_df = pd.DataFrame(results, columns=new_cols, index=df.index)
df = pd.concat([df, extract_df], axis=1)
2.7 保存结果为excel文件
核心代码:
df.to_excel("近一个月中标数据标签_已提取中标信息_多线程版.xlsx", index=False)
作者简介:
读研期间发表6篇SCI数据挖掘相关论文,现在某研究院从事数据算法相关科研工作,结合自身科研实践经历不定期分享关于Python、机器学习、深度学习、人工智能系列基础知识与应用案例。致力于只做原创,以最简单的方式理解和学习,关注我一起交流成长。需要数据集和源码的小伙伴可以关注底部公众号添加作者微信。
更多推荐



所有评论(0)