从20GB大型CSV按EMP_Code提取行时数据丢失的解决方案咨询
解决方案
先排查你第二个代码生成空文件的核心原因:
- 分隔符不匹配:你的示例中
master_file.csv用空格分隔,但csv.DictReader默认用逗号,需手动指定分隔符(比如delimiter=' ');若为不规则多空格,需改用字符串分割处理。 - 格式不一致:两边
EMP_Code可能存在前后空格、大小写差异,需提前清洗。 - 查询效率问题:用列表做
in查询效率极低,换成集合能大幅提升匹配速度。
针对20GB大文件的内存问题,推荐以下几种内存友好的处理方案:
方法1:CSV逐行读写(最低内存占用)
全程不加载大文件到内存,逐行判断并写入结果,适合超大型文件:
import csv import pandas as pd # 读取并清洗file1的EMP_Code,转成集合提升查询效率 df_file1 = pd.read_csv("file1.csv") target_codes = set(df_file1["EMP_Code"].str.strip()) # 处理master_file,逐行读取匹配 with open("master_file.csv", "r") as infile, open("Employee_full_data.csv", "w", newline="") as outfile: # 处理表头(根据实际分隔符调整,这里用空格) header_line = infile.readline().strip() header = header_line.split() writer = csv.writer(outfile, delimiter=",") writer.writerow(header) # 定位EMP_Code的列索引 code_idx = header.index("EMP_Code") # 逐行处理数据 for line in infile: line = line.strip() if not line: continue row = line.split() emp_code = row[code_idx].strip() if emp_code in target_codes: writer.writerow(row)
方法2:Pandas分块读取
用chunksize分块加载大文件,每块处理后追加写入结果:
import pandas as pd # 读取目标代码集合 df_file1 = pd.read_csv("file1.csv") target_codes = set(df_file1["EMP_Code"].str.strip()) # 分块读取master_file(每块10000行,可根据内存调整) chunk_size = 10000 first_write = True # sep="\s+"处理多空格分隔,实际为逗号则去掉该参数 for chunk in pd.read_csv("master_file.csv", sep="\s+", chunksize=chunk_size): # 清洗并匹配 chunk["EMP_Code"] = chunk["EMP_Code"].str.strip() matched_rows = chunk[chunk["EMP_Code"].isin(target_codes)] # 写入结果,仅第一次写入表头 matched_rows.to_csv( "Employee_full_data.csv", index=False, mode="a", header=first_write ) first_write = False
方法3:命令行awk工具(最高效)
无需Python代码,用系统原生工具处理,速度最快且内存占用极低:
# 提取file1的EMP_Code(跳过表头)存到临时文件 awk -F ',' '{print $2}' file1.csv | tail -n +2 > target_codes.txt # 匹配master_file中符合条件的行($4对应master_file中EMP_Code的列位置,需根据实际调整) awk 'NR==FNR {codes[$1]; next} $4 in codes' target_codes.txt master_file.csv > Employee_full_data.csv
关键注意事项
- 必须确保两边
EMP_Code格式完全一致:提前去除前后空格、统一大小写(比如str.lower())。 - 优先用集合存储目标代码,集合的
in查询效率比列表高几个数量级。 - 处理超大型文件时,避免一次性加载整个文件到内存,优先选择逐行或分块方案。
内容的提问来源于stack exchange,提问作者Shourya
相关产品推荐
相关产品推荐

