如何用Python为CSV缺失X/Y值的行补全上行对应值?
用Python补全CSV中缺失的X/Y值
你的原始CSV内容如下:
X310.433,Y9.6 X310.54,Y10 X143.52 X144.77
下面是实现补全逻辑的Python代码,核心思路是逐行读取记录,保存上一行完整的X、Y值,遇到缺失项时直接复用:
# 定义输入输出文件路径 input_path = "input.csv" output_path = "output.csv" # 初始化上一行的X、Y值 last_x = None last_y = None with open(input_path, 'r', encoding='utf-8') as in_file, open(output_path, 'w', encoding='utf-8') as out_file: for raw_line in in_file: line = raw_line.strip() if not line: continue # 跳过空行 # 分割当前行的X、Y项 items = line.split(',') # 确定当前行的X值:有则用当前值,无则用上一行的 current_x = items[0] if len(items) > 0 and items[0] else last_x # 确定当前行的Y值:有则用当前值,无则用上一行的 current_y = items[1] if len(items) > 1 and items[1] else last_y # 更新上一行的记录值(仅当当前行有有效值时更新) if current_x: last_x = current_x if current_y: last_y = current_y # 写入补全后的行 out_file.write(f"{current_x},{current_y}\n")
执行代码后,输出的CSV内容如下:
X310.433,Y9.6 X310.54,Y10 X143.52,Y10 X144.77,Y10
逻辑说明
- 先初始化
last_x和last_y来存储上一行的有效X、Y值 - 逐行读取文件,跳过空行后分割内容
- 对X、Y值分别判断:当前行有值就用当前值,没有就复用
last_x/last_y - 每次处理完一行后,更新
last_x/last_y为当前行的有效值,确保后续行能正确复用 - 最后将补全后的行写入新文件
内容的提问来源于stack exchange,提问作者volk.SWAG.en
相关产品推荐
相关产品推荐

