提问人:mggo256 提问时间:9/27/2023 更新时间:9/28/2023 访问量:66
有没有办法使用 pandas str.replace 仅在单词单独出现时替换它,而不是作为较长字符串的一部分?
Is there a way using pandas str.replace to replace a word ONLY when it occurs by itself, rather than as part of a longer string?
问:
我有一个数据帧,当它作为数据帧中的单个项目/单元格/条目单独出现时,我只想替换“Blah”——而不是作为像“Blah guh”这样的较长字符串的一部分。请参阅以下示例:
data={"Col":["Blah","Blah gah","Blah bluh"],'Subs':["one","two","three"]}
df=pd.DataFrame(data)
期望输出:
山坳 | 潜艇 |
---|---|
等等 | 一 |
咻 | 二 |
咻 | 三 |
我尝试使用单词边界,但它只是在所有三个条目中替换了 Blah......
df["Col"] = df["Col"].str.replace(r'\bBlah\b', "Blah ALL", regex=True)
山坳 | 潜艇 |
---|---|
等等 | 一 |
等等 | 二 |
等等 ALL bluh | 三 |
很确定我在这里遗漏了一些明显的东西。
答:
2赞
esqew
9/27/2023
#1
不要使用单词边界 (),而是选择字符串开始/结束锚点 (/):\b
^
$
df["Col"] = df["Col"].str.replace(r'^Blah$', "Blah ALL", regex=True)
1赞
butterflyknife
9/27/2023
#2
这是否就像确保单元格以“Blah”开头和结尾一样简单吗?因为如果是这样:
df["Col"] = df["Col"].str.replace(r'^Blah$', "Blah ALL", regex=True)
评论
1赞
mggo256
9/28/2023
是的,这奏效了......我肯定需要学习更多的正则表达式,感谢您的帮助
0赞
butterflyknife
9/28/2023
@mggo256:这个网站真的让我整理好了:regexone.com
0赞
mozway
9/28/2023
#3
当您需要替换完整字符串时不要使用,而是使用 replace
(默认):str.replace
regex=False
df['Col'] = df['Col'].replace('Blah', 'Blah ALL')
输出:
Col Subs
0 Blah ALL one
1 Blah gah two
2 Blah bluh three
计时
这也快得多。
在 30k 行上:
# replace
3.9 ms ± 450 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# str.replace with regex=True
37.2 ms ± 3.57 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
评论
df['Col'].replace('Blah', 'Blah ALL')
series.replace
与 不同,默认情况下仅替换整个单元格值。.str.replace