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

如何用Python替换CSV文件第一列为指定列表值

使用Python替换CSV文件第一列为指定列表值

问题背景

需要将CSV文件的第一列替换为指定的药物名称列表,相关数据如下:

原始CSV数据

0   1   2   3   4   5   6   7   8   9
0   0   0   0.3 0   0.3 0   0.3 0   0   0
1   0   0.2 0   0   0   0   0.2 0.4 0.2 0
2   0   0   0.2 0.1 0.3 0.1 0   0.4 0   0
3   0   0   0.1 0.2 0.1 0.1 0.2 0.1 0.1 0.1
4   0   0   0.2 0.1 0   0.1 0.2 0.2 0.2 0.1
5   0   0   0   0   0   0.3 0.3 0   0.3 0
6   0   0   0.3 0   0   0.3 0   0.3 0   0
7   0   0   0.1 0.2 0.1 0.1 0.1 0.2 0.1 0.2
8   0   0   0.1 0.1 0.1 0   0.1 0.1 0.3 0
9   0   0   0.1 0.1 0.1 0.1 0.1 0.2 0.1 0.1

替换用的目标列表

['ZINC53 (Aspirin)', 'ZINC7460 (Vatalanib)', 'ZINC1493878 (Sorafenib)', 'ZINC1546066 (Erlotinib)', 'ZINC1550477 (Lapatinib)', 'ZINC3964325 (Sunitinib)', 'ZINC13550868 (Acetaminophen)', 'ZINC19632614 (Iressa)', 'ZINC19632618 (Imatinib)', 'ZINC27439698 (Canertinib)']

期望输出

0   1   2   3   4   5   6   7   8   9
ZINC53 (Aspirin)    0   0   0.3 0   0.3 0   0.3 0   0   0
ZINC7460 (Vatalanib)    0   0.2 0   0   0   0   0.2 0.4 0.2 0
ZINC1493878 (Sorafenib) 0   0   0.2 0.1 0.3 0.1 0   0.4 0   0
ZINC1546066 (Erlotinib) 0   0   0.1 0.2 0.1 0.1 0.2 0.1 0.1 0.1
ZINC1550477 (Lapatinib) 0   0   0.2 0.1 0   0.1 0.2 0.2 0.2 0.1
ZINC3964325 (Sunitinib) 0   0   0   0   0   0.3 0.3 0   0.3 0
ZINC13550868 (Acetaminophen)    0   0   0.3 0   0   0.3 0   0.3 0   0
ZINC19632614 (Iressa)   0   0   0.1 0.2 0.1 0.1 0.1 0.2 0.1 0.2
ZINC19632618 (Imatinib) 0   0   0.1 0.1 0.1 0   0.1 0.1 0.3 0
ZINC27439698 (Canertinib)   0   0   0.1 0.1 0.1 0.1 0.1 0.2 0.1 0.1

解决方案(使用Pandas)

Pandas是处理CSV数据的高效工具,以下代码可快速完成需求:

import pandas as pd

# 1. 读取CSV文件,指定第一列为索引
df = pd.read_csv('input.csv', index_col=0)

# 2. 定义替换用的目标列表
new_index_values = [
    'ZINC53 (Aspirin)',
    'ZINC7460 (Vatalanib)',
    'ZINC1493878 (Sorafenib)',
    'ZINC1546066 (Erlotinib)',
    'ZINC1550477 (Lapatinib)',
    'ZINC3964325 (Sunitinib)',
    'ZINC13550868 (Acetaminophen)',
    'ZINC19632614 (Iressa)',
    'ZINC19632618 (Imatinib)',
    'ZINC27439698 (Canertinib)'
]

# 3. 替换第一列(索引)
df.index = new_index_values

# 4. 保存修改后的CSV文件
df.to_csv('output.csv')

# 可选:打印结果查看
print(df)

注意事项

  • 如果你的CSV文件第一列不是索引,而是普通列(列名为0),可将替换步骤改为:df['0'] = new_index_values
  • 确保目标列表的长度与CSV的行数一致,否则会报错
  • 若未安装Pandas,先执行pip install pandas安装

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:46:16