python - 如何替换pandas str中的+xx替换

标签 python pandas

我正在使用Python 2.7.12pandas 0.20.3,我有一个如下所示的数据框,我想替换名为number的列,该列dtype是对象,当我尝试替换该列中的 +91 时,我收到如下错误,

          number
0  +9185600XXXXX
1  +9199651XXXXX
2     99211XXXXX
3     99341XXXXX
4  +9199651XXXXX

sre_constants.error:没有什么可重复的

完整跟踪,

Traceback (most recent call last): File "encoder.py", line 21, in df['number']=df['number'].str.replace('+91','') File "/home/hduser/.local/lib/python2.7/site-packages/pandas/core/strings.py", line 1574, in replace flags=flags) File "/home/hduser/.local/lib/python2.7/site-packages/pandas/core/strings.py", line 424, in str_replace regex = re.compile(pat, flags=flags) File "/usr/lib/python2.7/re.py", line 194, in compile return _compile(pattern, flags) File "/usr/lib/python2.7/re.py", line 251, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat

但是当我替换 91 时,它按我的预期工作,当我将 + 放在前缀中时,它不起作用, 请帮我解决这个问题。

错误发生在,

df['number']=df['number'].str.replace('+91','')
<小时/>

最佳答案

您可以转义特殊的正则表达式值+(一个或多个重复),例如:

df['number'] = df['number'].str.replace('\+91','')

或者使用参数regex=False:

df['number'] = df['number'].str.replace('+91','', regex=False)

关于python - 如何替换pandas str中的+xx替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52384190/

相关文章:

python - 如果该行中的所有值都是假的,Pandas 会删除该行

python - 持续接收来自Azure ServiceBus的消息

python - 字典每个键分为多行

python - 切换数据框中的行和列

python - 使用 Pandas 石斑鱼时如何取系列的最大值?

根据另一列的匹配条件更新 Polars 数据框的一列的 Pythonic 方法

python - 正则表达式,如何匹配第 n 次出现之前的所有内容

python - 在 python 中使用为 R 编写的 R 脚本

python - 如何根据pandas中的多个条件匹配和计算行?

python - 优化 "group by"并保持最大值或最小值 - MySQL/Python