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

如何用Python(含/不含Pandas)通过NAME匹配为CSV-1填充ID值

实现方法:根据NAME匹配填充CSV-1的ID列

方法一:使用Pandas(高效简洁)

如果环境允许安装第三方库,Pandas是最便捷的方案:

  1. 未安装Pandas的话先执行安装命令:
pip install pandas
  1. 核心实现代码:
import pandas as pd

# 读取两个CSV文件
csv1 = pd.read_csv('csv1.csv')
csv2 = pd.read_csv('csv2.csv')

# 构建NAME到ID的映射字典(若CSV-2有重复NAME,会保留最后一行的ID)
id_mapping = csv2.set_index('NAME')['ID'].to_dict()

# 根据NAME匹配填充ID列
csv1['ID'] = csv1['NAME'].map(id_mapping)

# 保存填充后的结果
csv1.to_csv('filled_csv1.csv', index=False)

注意事项:

  • 如果CSV-2存在重复的NAME值,上述代码会用最后出现的ID覆盖之前的;若要保留第一个出现的ID,可先对CSV-2去重:
    csv2 = csv2.drop_duplicates(subset='NAME', keep='first')
    

方法二:纯Python标准库(无额外依赖)

如果无法安装第三方库,用Python自带的csv模块即可实现:

import csv

# 从CSV-2提取NAME与ID的映射关系
id_mapping = {}
with open('csv2.csv', 'r', newline='', encoding='utf-8') as csv2_file:
    reader = csv.DictReader(csv2_file)
    for row in reader:
        # 重复NAME会被后续行的ID覆盖,可根据需求调整逻辑
        id_mapping[row['NAME']] = row['ID']

# 读取CSV-1并填充ID,输出新文件
with open('csv1.csv', 'r', newline='', encoding='utf-8') as csv1_file, \
     open('filled_csv1.csv', 'w', newline='', encoding='utf-8') as output_file:
    reader = csv.DictReader(csv1_file)
    fieldnames = reader.fieldnames  # 保留原CSV的列顺序
    writer = csv.DictWriter(output_file, fieldnames=fieldnames)
    
    writer.writeheader()
    for row in reader:
        # 匹配NAME对应的ID,无匹配则保留原空值(可替换为'N/A'等默认值)
        row['ID'] = id_mapping.get(row['NAME'], row['ID'])
        writer.writerow(row)

注意事项:

  • 若NAME无匹配项,ID列会保持原CSV-1的空值;如果需要设置默认值,把row['ID'] = id_mapping.get(row['NAME'], row['ID'])中的第二个参数改成你需要的值即可,比如'N/A'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:37:26