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

如何用字典替换Pandas DataFrame单元格内的多片段字符串?

解决Pandas中逗号分隔字符串批量映射字典值的问题

问题场景

现有Pandas DataFrame的Article列,单元格内容为逗号分隔的字符串(含空值),示例如下:

df_lost['Article']

# 输出:
37774    186-2, 185-3, 185-2
37850           358-1, 358-4
37927                       
38266                  111-2
38409                  111-2
38508                       
38519                  185-1
41161           185-4, 357-1
42948                  185-1
Name: Article, dtype: object

另有映射字典aDict,键为字符串片段,值为对应替换文本:

aDict = {'111-2': 'Text-1', '358-1': 'Text-2', ...}

直接使用df['Article'].map(aDict)无法处理多片段的单元格,临时将完整组合字符串作为字典键的方案因组合数量过大不具备可行性,需更优解。

解决方案

方法一:拆分-映射-聚合

通过拆分字符串、展开映射、再聚合的方式完成批量替换,逻辑清晰,适用于需要中间步骤处理的场景:

import pandas as pd

# 示例数据(可替换为你的实际数据)
data = {
    'Article': ['186-2, 185-3, 185-2', '358-1, 358-4', '', '111-2', '111-2', '', '185-1', '185-4, 357-1', '185-1']
}
df_lost = pd.DataFrame(data, index=[37774, 37850, 37927, 38266, 38409, 38508, 38519, 41161, 42948])

# 映射字典(补充示例键值,实际替换为你的字典)
aDict = {'111-2': 'Text-1', '358-1': 'Text-2', '186-2': 'Text-3', '185-3': 'Text-4', '185-2': 'Text-5', '358-4': 'Text-6', '185-1': 'Text-7', '185-4': 'Text-8', '357-1': 'Text-9'}

# 批量映射逻辑
df_lost['Mapped_Article'] = (
    df_lost['Article']
    .str.split(', ')  # 按逗号加空格拆分字符串为列表
    .apply(lambda x: [] if x == [''] else x)  # 处理空字符串转为空列表
    .explode()  # 将列表展开为单行单个元素
    .map(aDict)  # 用字典映射对应值
    .groupby(level=0)  # 按原DataFrame的索引分组
    .agg(', '.join)  # 将分组后的元素合并为逗号分隔字符串
    .fillna('')  # 空值填充为空字符串
)

# 查看结果
print(df_lost['Mapped_Article'])

方法二:apply结合列表推导式

更简洁的单步处理方式,直接在单元格内完成每个片段的映射,效率更高:

df_lost['Mapped_Article'] = df_lost['Article'].apply(
    lambda x: ', '.join([aDict.get(item.strip(), item.strip()) for item in x.split(',') if item.strip()])
)
  • item.strip()用于去除片段前后的空格,避免因空格导致字典匹配失败;
  • aDict.get(item.strip(), item.strip())确保找不到对应键时保留原片段(也可将第二个参数改为''或其他默认值);
  • if item.strip()过滤掉空的片段,避免生成多余的逗号。

输出结果示例

处理后Mapped_Article列的输出如下:

37774    Text-3, Text-4, Text-5
37850           Text-2, Text-6
37927                        
38266                  Text-1
38409                  Text-1
38508                        
38519                  Text-7
41161           Text-8, Text-9
42948                  Text-7
Name: Mapped_Article, dtype: object

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:55:17