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

DataFrame中根据字典键匹配插入对应值的问题求助

解决DataFrame匹配字典键生成对应值列的问题

你的代码返回空列表的核心问题是:直接遍历了字符串的单个字符,而非分割后的单词。比如处理"vs, vscode"时,for word in row_value会逐个取出'v'、's'、','这类字符,这些字符不在字典键中,自然返回空列表。

修正方案

调整逻辑,先分割字符串为单词列表,再匹配字典值,最后处理结果格式:

import pandas as pd
import numpy as np

df = pd.DataFrame({'key' : ["vs, vscode", "jupyter, jupyterlab", "python, vs", "python", "it was spyder before dawn"]})

my_dict = {'vscode' : 'is gross',
           'jupyter' : 'is not so awesome, but hes ok, ig',
           'vs' : 'is awesome',
           'jupyterlab' : 'is rad',
          'python' : "booya"}

def cascade_col(row_value):
    # 按", "分割字符串,得到单词列表
    words = row_value.split(', ')
    matched_values = []
    for word in words:
        if word in my_dict:
            matched_values.append(my_dict[word])
    # 有匹配值则拼接成字符串,无匹配则返回np.nan
    return ', '.join(matched_values) if matched_values else np.nan

df['Corresponding Value(s)'] = df['key'].apply(cascade_col)

print(df)

运行结果

输出完全符合你的预期:

key                          Corresponding Value(s)
0                      vs, vscode                          is awesome, is gross
1            jupyter, jupyterlab  is not so awesome, but hes ok, ig, is rad
2                   python, vs                          booya, is awesome
3                          python                                        booya
4  it was spyder before dawn                                         NaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:20:29