如何用csv或pandas批量替换CSV指定列的valueX为统一值Value3
替换CSV指定列的统一值方案
给你两种实用的实现方案,对应你提到的csv库和pandas模块:
一、使用Python内置csv库
你的CSV包含带引号、含特殊字符的字段,直接字符串分割会出错,必须用csv模块正确解析:
import csv # 输入输出文件路径可根据实际修改 input_file = "input.csv" output_file = "output.csv" with open(input_file, 'r', encoding='utf-8') as infile, \ open(output_file, 'w', encoding='utf-8', newline='') as outfile: reader = csv.reader(infile) writer = csv.writer(outfile) for row in reader: # 替换第12个字段(索引从0开始是11)为"Value3" if len(row) >= 12: # 避免行长度不足导致索引越界 row[11] = "Value3" writer.writerow(row)
二、使用pandas模块
如果数据量较大,pandas处理效率更高,代码也更简洁:
import pandas as pd # 读取CSV,注意设置正确编码(比如utf-8) df = pd.read_csv("input.csv", header=None, encoding='utf-8') # 替换第12列(索引11)的值为"Value3" df.iloc[:, 11] = "Value3" # 保存修改后的CSV,不写入索引列 df.to_csv("output.csv", header=False, index=False, encoding='utf-8')
注:两种方案都会保留原CSV的引号、特殊字符格式,确保数据结构不被破坏。
内容的提问来源于stack exchange,提问作者MarkKoler
相关产品推荐
相关产品推荐

