提问人:sdbbs 提问时间:10/30/2023 更新时间:10/30/2023 访问量:58
Pandas str.replace with regex doubles 结果?[复制]
Pandas str.replace with regex doubles results? [duplicate]
问:
假设我有这个熊猫系列:
$ python3 -c 'import pandas as pd; print(pd.Series(["1","2","3","4"]))'
0 1
1 2
2 3
3 4
dtype: object
我想“包装”字符串“1”,“2”,“3”,“4”,因此它们以“a”为前缀,并以“b”->为后缀,也就是说,我想得到“a1b”,“a2b”,“a3b”,“a4b”。所以我试着 https://pandas.pydata.org/docs/reference/api/pandas.Series.str.replace.html
$ python3 -c 'import pandas as pd; print(pd.Series(["1","2","3","4"]).str.replace("(.*)", r"a\1b", regex=True))'
0 a1bab
1 a2bab
2 a3bab
3 a4bab
dtype: object
所以 - 我确实将“1”“包装”到“a1b”->但随后“ab”又重复了一次?
(在 regex101.com 尝试这个正则表达式时,我注意到如果启用了该标志,我会得到与“ab”相同的“幽灵副本”;所以也许 Pandas 以某种方式启用了它?但是,根据文档,默认是 Pandas ?!g
.str.replace
flags=0
.str.replace
如何让列单元格的全部内容“包装”在我想要的字符中?
答:
1赞
Andrej Kesely
10/30/2023
#1
更改为 :(.*)
(.+)
andrej@Andrej-PC:~/app$ python3 -c 'import pandas as pd; print(pd.Series(["1","2","3","4"]).str.replace("(.+)", r"a\1b", regex=True))'
0 a1b
1 a2b
2 a3b
3 a4b
dtype: object
评论
1赞
sdbbs
10/30/2023
非常感谢,接受这个答案,因为方法与 OP(使用正则表达式)完全相同
0赞
Scott Boston
10/30/2023
但是为什么?我们需要将 * 更改为 + 吗?*是贪婪的,但我想解释为什么。+1
1赞
Andrej Kesely
10/30/2023
@ScottBoston表示匹配任何字符零次或多次。这意味着它与字符串末尾的零长度值匹配(这就是您在输出中看到的原因)。这意味着角色必须至少匹配一次。.*
.
a1bab
.+
0赞
Scott Boston
10/30/2023
@AndrejKesely 啊,是的。我理解。谢谢!因此,使用 * 时的贪婪术语。
0赞
PaulS
10/30/2023
#2
一个可能的解决方案:
s = pd.Series(range(1,5))
'a' + s.astype(str) + 'b'
输出:
0 a1b
1 a2b
2 a3b
3 a4b
dtype: object
评论