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

基于CSV文件结构匹配批量添加条码列的代码实现需求

Python 解决方案(适合编程新手)

操作步骤

  • 先安装处理CSV的常用库pandas
  • 读取两个目标CSV文件
  • 从File_2.csv中创建「Structure -> Barcode」的映射字典(因Structure列值唯一,字典匹配效率高)
  • 为File_1.csv的三个Structure列分别匹配对应条码,生成新列
  • 保存结果到输出文件

代码实现

import pandas as pd

# 读取CSV文件
file1 = pd.read_csv("File_1.csv")
file2 = pd.read_csv("File_2.csv")

# 构建Structure与Barcode的映射字典
structure_barcode_map = dict(zip(file2["Structure"], file2["Barcodes"]))

# 添加三个Barcode列
file1["Barcode_1"] = file1["Structure_1"].map(structure_barcode_map)
file1["Barcode_2"] = file1["Structure_2"].map(structure_barcode_map)
file1["Barcode_3"] = file1["Structure_3"].map(structure_barcode_map)

# 保存结果(不生成多余索引列)
file1.to_csv("File_3_output.csv", index=False)

代码说明

  • pd.read_csv():将CSV文件转换成易操作的表格格式(DataFrame)
  • dict(zip(...)):把File_2.csv的Structure和Barcodes列配对,生成键值对字典,快速查找条码
  • .map():自动将每个Structure值替换为对应的Barcode,支持重复值匹配
  • to_csv(index=False):确保输出文件和示例格式一致,无额外索引列

运行注意

  • 确保File_1.csv、File_2.csv和代码在同一文件夹
  • 未安装pandas的话,先在终端执行:pip install pandas

R 解决方案

代码实现

# 读取CSV文件
file1 <- read.csv("File_1.csv")
file2 <- read.csv("File_2.csv")

# 构建Structure到Barcode的映射
structure_barcode_map <- setNames(file2$Barcodes, file2$Structure)

# 添加三个Barcode列
file1$Barcode_1 <- structure_barcode_map[file1$Structure_1]
file1$Barcode_2 <- structure_barcode_map[file1$Structure_2]
file1$Barcode_3 <- structure_barcode_map[file1$Structure_3]

# 保存结果(不生成行名)
write.csv(file1, "File_3_output.csv", row.names = FALSE)

Bash 解决方案(适合有Bash基础的用户)

注:仅适用于无逗号嵌套的简单CSV格式

awk '
BEGIN {
    FS = ","; OFS = ","
    # 读取File_2构建映射
    while ((getline < "File_2.csv") > 0) {
        if (NR == 1) { next }  # 跳过表头
        structure_barcode_map[$3] = $4
    }
    close("File_2.csv")
}
# 处理File_1
NR == 1 {
    print $0, "Barcode_1", "Barcode_2", "Barcode_3"  # 追加新表头
    next
}
{
    barcode1 = structure_barcode_map[$5]
    barcode2 = structure_barcode_map[$6]
    barcode3 = structure_barcode_map[$7]
    print $0, barcode1, barcode2, barcode3
}
' File_1.csv > File_3_output.csv

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 06:25:06