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

如何在Python中基于指定Bin_Name实现CSV数据的类VLOOKUP匹配?

Python实现指定Bin_Name的类VLOOKUP功能

实现思路

  1. 从CSV2中定位目标Bin_Name对应的Quantity值
  2. 遍历CSV1,仅更新匹配目标Bin_Name的行的Quantity列
  3. 将更新后的数据写回CSV1(建议操作前备份原文件)

代码实现

import csv

# 配置参数:修改这里的目标Bin_Name和文件路径
target_bin = "A"  # 替换成你需要的Bin_Name,比如"ABCDE"
csv1_path = "csv1.csv"
csv2_path = "csv2.csv"

# 步骤1:从CSV2获取目标Bin_Name对应的Quantity值
quantity_value = None
with open(csv2_path, mode='r', newline='', encoding='utf-8') as csv2_file:
    reader = csv.DictReader(csv2_file)
    for row in reader:
        if row['Bin_Name'] == target_bin:
            quantity_value = row['Quantity']
            break

if quantity_value is None:
    print(f"CSV2中未找到Bin_Name为{target_bin}的数据")

# 步骤2:读取CSV1并更新对应行的Quantity
updated_rows = []
with open(csv1_path, mode='r', newline='', encoding='utf-8') as csv1_file:
    reader = csv.DictReader(csv1_file)
    fieldnames = reader.fieldnames  # 保留原表头
    for row in reader:
        if row['Bin_Name'] == target_bin:
            row['Quantity'] = quantity_value
        updated_rows.append(row)

# 步骤3:将更新后的数据写回CSV1
with open(csv1_path, mode='w', newline='', encoding='utf-8') as csv1_file:
    writer = csv.DictWriter(csv1_file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(updated_rows)

print(f"已完成Bin_Name为{target_bin}的Quantity更新")

代码说明

  • 使用Python标准库csv的DictReader/DictWriter,通过列名访问数据,无需依赖第三方库
  • 仅更新指定Bin_Name的行,其他行保持原数据不变
  • 若CSV文件编码为GBK等非UTF-8,需修改encoding参数为对应编码
  • 若CSV2中无目标Bin_Name,会打印提示且不修改CSV1对应行

注意事项

  • 操作前务必备份原CSV文件,避免意外导致数据丢失
  • 如果需要批量处理多个Bin_Name,可将target_bin改为列表,通过循环实现批量更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:10:26