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

如何在Python Pandas DataFrame的逗号分隔文本列中用单个词替换文本片段?

问题原因及解决方法

你的代码有三个关键问题导致替换没生效:

  1. 字典键值写反了:你要把长片段(比如"i am hungry")替换成短词("hungry"),但原字典里是把短词作为键、长片段作为值,这相当于让程序做反向替换,自然看不到效果。
  2. 未初始化DataFrame:代码里直接用了df但没把data转换成DataFrame对象,会直接报错。
  3. 缺少正则匹配参数:默认replace是精确匹配整串文本,而你要替换的是文本里的子片段,必须开启regex=True才能让程序识别子串。

修正后的代码

import pandas as pd

data = {"col": ['i am hungry, you are pretty', 'i am hungry, you are pretty, i love flowers', 
              'i am hungry, i love flowers', 'i am hungry,choccies are nice']} 
# 先把数据转换成DataFrame
df = pd.DataFrame(data)

# 修正键值对:键是要被替换的长文本,值是目标短词
replace_dict = {
    'i am hungry': 'hungry', 
    'you are pretty': 'pretty',
    'i love flowers': 'flowers',
    'choccies are nice': 'choccies'
}

# 开启regex=True,匹配子串进行替换
new_df = df.replace({"col": replace_dict}, regex=True)
print(new_df)

输出结果

col
0        hungry, pretty
1  hungry, pretty, flowers
2        hungry, flowers
3        hungry,choccies

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:47:09