首页 > 解决方案 > Pandas Dataframe Replace 不适用于子句

问题描述

我有一个带有 A 列的数据框,其中包含以下形式的值:

Col A

this is to be replaced
nonsense, this is to be replaced
nonsense
garbage
this is to be replace, nonsense

理想输出:

Col A

this has been replaced
nonsense, this has been replaced
nonsense
garbage
this has been replaced, nonsense

我试过了:

df['Col A'].replace('this is to be replaced', 'this has been replaced')
df['Col A'].str.replace('this is to be replaced', 'this has been replaced', regex=True, inplace=True)
df['Col A'].replace({'this is to be replaced':'this has been replaced'}, regex=True, inplace=True)
df['Col A'].replace(regex= ['this is to be replaced'], value= 'this has been replaced')

基本上所有解决这个问题的标准方法。问题似乎是子字符串中的空格。当我尝试替换特定单词时,它可以正常工作。

有任何想法吗?

编辑:我尝试了你们所有的建议,但它们不起作用。作为附加上下文:

要替换的确切字符串是:

MATHEMATICS (Math 1601 & 1602)

MATHEMATICS (Math 1601 & Math 1602)

我也试过:

df['col A'] = df['col A'].replace('1602', 'Math 1602')

标签: pythonregexpandasdataframereplace

解决方案


这是你想要的?

df = pd.DataFrame({'Col A':
['this is to be replaced',
'nonsense, this is to be replaced',
'nonsense',
'garbage',
'this is to be replace, nonsense']})
df.replace(to_replace=['is to be'], value = 'has been', regex = True, inplace = True)
df

在此处输入图像描述


推荐阅读