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

如何依据字典匹配条件向Pandas DataFrame列追加字符串?

需求实现与优化建议

需求明确

要实现的功能是:检查字典d1中的每个键是否存在于DataFrame的Layers列字符串中,将所有匹配到的字典值用连字符-拼接,生成新列(比如Layers包含BR和TERR,新列值为Bridge-Terrain)。

现有代码问题

你当前的代码存在几个明显问题:

  • 语法错误:for i in df.Layers末尾缺少冒号:
  • 逻辑错误:只遍历字典的第一个键,没有检查所有键是否匹配
  • 操作错误:用df1.append的方式无法正确生成新列,反而会创建一个新的DataFrame,且效率极低

解决方案

方案一:创建DataFrame前预处理(你关注的方式)

在构建原始数据字典mapping时,直接生成新列的对应值,再创建DataFrame,步骤如下:

# 原始数据
mapping = {'IDs': [1244, 35673, 37863, 76373, 234298],
 'Layers': ['D-BR-PILECAPS-OUTLINE 2',
  'D-BR-STEEL-OUTLINE 2D-TERR-BOUNDARY',
  'D-SUBG-OTHER',
  'D-COMP-PAVE-CONC2',
  'D-EWKS-HINGE']}

# 匹配字典
d1 = {"BR": "Bridge", "EWKS": "Earthworks", "KERB": "Kerb", "TERR": "Terrain"}

# 预处理生成新列数据
category_values = []
for layer_str in mapping['Layers']:
    # 收集所有匹配到的值
    matches = [val for key, val in d1.items() if key in layer_str]
    # 拼接结果,无匹配则留空
    category = '-'.join(matches) if matches else ''
    category_values.append(category)

# 将新列加入原始数据字典
mapping['Category'] = category_values

# 创建DataFrame
df = pd.DataFrame(mapping)
print(df)

运行后输出的DataFrame会包含新列Category,值分别为Bridge、Bridge-Terrain、空字符串、空字符串、Earthworks。

方案二:创建DataFrame后用apply处理(更符合Pandas风格)

如果已经生成了DataFrame,用apply函数逐行处理Layers列,代码更简洁高效:

import pandas as pd

# 原始数据与匹配字典
mapping = {'IDs': [1244, 35673, 37863, 76373, 234298],
 'Layers': ['D-BR-PILECAPS-OUTLINE 2',
  'D-BR-STEEL-OUTLINE 2D-TERR-BOUNDARY',
  'D-SUBG-OTHER',
  'D-COMP-PAVE-CONC2',
  'D-EWKS-HINGE']}
d1 = {"BR": "Bridge", "EWKS": "Earthworks", "KERB": "Kerb", "TERR": "Terrain"}

# 创建DataFrame
df = pd.DataFrame(mapping)

# 定义匹配函数
def generate_category(layer):
    matches = [val for key, val in d1.items() if key in layer]
    return '-'.join(matches) if matches else ''

# 生成新列
df['Category'] = df['Layers'].apply(generate_category)
print(df)

方案对比

  • 预处理方式:适合数据量较小、需要提前完成数据整理的场景,逻辑直观
  • apply方式:更贴合Pandas的使用习惯,代码更简洁,处理大型数据集时效率优于手动循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:35:24