You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python通过列表批量替换CSV文件指定列的数值?

Python 替换CSV指定列值的实现方案

以下提供两种实现方式,可根据自己的需求选择:

方法1:使用pandas实现(代码更简洁,推荐)

  • 先安装依赖:pip install pandas
  • 完整代码示例:
import pandas as pd

# 替换用的数值列表
replace_list = [8,5,3,4,5,7,3,5]
# 读取本地CSV文件,替换为你自己的文件路径
df = pd.read_csv("your_file.csv")
# 按顺序替换Items列的所有值
df["Items"] = replace_list
# 保存修改后的文件,不保留pandas自动生成的索引列
df.to_csv("updated_file.csv", index=False)
  • 注意:需保证replace_list的长度和CSV文件中Items列的数据行数完全一致,否则会执行报错。

方法2:使用Python内置csv模块实现(无需安装第三方依赖)

  • 完整代码示例:
import csv

replace_list = [8,5,3,4,5,7,3,5]
# 读取原CSV内容
with open("your_file.csv", "r", encoding="utf-8") as rf:
    reader = csv.DictReader(rf)
    data_rows = list(reader)
    headers = reader.fieldnames
    # 逐行替换Items列的值
    for index, row in enumerate(data_rows):
        row["Items"] = replace_list[index]

# 写入修改后的内容到新文件
with open("updated_file.csv", "w", encoding="utf-8", newline="") as wf:
    writer = csv.DictWriter(wf, fieldnames=headers)
    writer.writeheader()
    writer.writerows(data_rows)

内容的提问来源于stack exchange,提问作者DragonKing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 13:39:03