str.replace 有问题
Trouble with str.replace
这是我遇到的问题。
dataframe 中的原始列包含这样的保险名称 "(Do Not Use) Healthfirst"
,而该列的名称是 "InsuranceNames"
。我正在使用以下代码尝试将 "(Do Not Use) "
部分替换为空白,只留下保险名称:
df["InsuranceNames"] = df["InsuranceNames"].str.replace('(Do Not Use) ','',regex=True)
但是当我将其导出到 csv 时,“请勿使用”仍然存在。为什么会这样?对此提供一些帮助将不胜感激。
您可能有两个问题之一或两者都有。
- 当您正在寻找完全匹配的字符串时,您不应使用正则表达式,因此您可以删除
regex=True
.
- 您在
'(Do Not Use) '
内的间距可能是错误的。只要 '(Do Not Use) '
不在字符串中的单词之间,您将获得更可靠的结果替换 '(Do Not Use)'
而不使用 space,然后使用 .strip()
删除额外的 space s 从字符串的末尾开始。
试试这个:
df["InsuranceNames"]=df["InsuranceNames"].apply(lambda x: x.replace('(Do Not Use)','').strip())
示例:
输入:
df=pd.DataFrame({"InsuranceNames":['(Do Not Use) Healthfirst', '(Do Not Use) Foobar',' (Do Not Use) Aflac','(Do Not Use) Foo ', '(Do Not Use) Bar']})
df:
InsuranceNames
0 (Do Not Use) Healthfirst
1 (Do Not Use) Foobar
2 (Do Not Use) Aflac
3 (Do Not Use) Foo
4 (Do Not Use) Bar
申请:
df["InsuranceNames"]=df["InsuranceNames"].apply(lambda x: x.replace('(Do Not Use)','').strip())
输出 df:
InsuranceNames
0 Healthfirst
1 Foobar
2 Aflac
3 Foo
4 Bar
这是我遇到的问题。
dataframe 中的原始列包含这样的保险名称 "(Do Not Use) Healthfirst"
,而该列的名称是 "InsuranceNames"
。我正在使用以下代码尝试将 "(Do Not Use) "
部分替换为空白,只留下保险名称:
df["InsuranceNames"] = df["InsuranceNames"].str.replace('(Do Not Use) ','',regex=True)
但是当我将其导出到 csv 时,“请勿使用”仍然存在。为什么会这样?对此提供一些帮助将不胜感激。
您可能有两个问题之一或两者都有。
- 当您正在寻找完全匹配的字符串时,您不应使用正则表达式,因此您可以删除
regex=True
. - 您在
'(Do Not Use) '
内的间距可能是错误的。只要'(Do Not Use) '
不在字符串中的单词之间,您将获得更可靠的结果替换'(Do Not Use)'
而不使用 space,然后使用.strip()
删除额外的 space s 从字符串的末尾开始。
试试这个:
df["InsuranceNames"]=df["InsuranceNames"].apply(lambda x: x.replace('(Do Not Use)','').strip())
示例:
输入:
df=pd.DataFrame({"InsuranceNames":['(Do Not Use) Healthfirst', '(Do Not Use) Foobar',' (Do Not Use) Aflac','(Do Not Use) Foo ', '(Do Not Use) Bar']})
df:
InsuranceNames
0 (Do Not Use) Healthfirst
1 (Do Not Use) Foobar
2 (Do Not Use) Aflac
3 (Do Not Use) Foo
4 (Do Not Use) Bar
申请:
df["InsuranceNames"]=df["InsuranceNames"].apply(lambda x: x.replace('(Do Not Use)','').strip())
输出 df:
InsuranceNames
0 Healthfirst
1 Foobar
2 Aflac
3 Foo
4 Bar