如何在熊猫str替换中替换+ xx

时间:2018-09-18 10:11:20

标签: python pandas

我正在使用Python 2.7.12pandas 0.20.3,我有一个如下所示的数据框,我想替换名为number的列,当我尝试替换{{1}时,此列dtype是object }在该列中,出现如下错误,

+91

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

完整跟踪,

  

回溯(最近通话最近):     在第21行的文件“ encoder.py”中       df ['number'] = df ['number']。str.replace('+ 91','')     在替换文件“ /home/hduser/.local/lib/python2.7/site-packages/pandas/core/strings.py”中,行1574       标志=标志)     在str_replace的第424行中添加文件“ /home/hduser/.local/lib/python2.7/site-packages/pandas/core/strings.py”       正则表达式= re.compile(pat,flags = flags)     编译中的文件“ /usr/lib/python2.7/re.py”,第194行       返回_compile(模式,标志)     _compile中的文件“ /usr/lib/python2.7/re.py”,第251行       引发错误,v#表达式无效   sre_constants.error:无需重复

但是当我替换sre_constants.error: nothing to repeat时,它按预期工作,当我将91放在前缀中时,它不工作, 请帮我解决这个问题。

发生错误,

+

2 个答案:

答案 0 :(得分:1)

您可以像这样转义特殊的正则表达式值+one or more repetitions

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

或使用参数regex=False

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

答案 1 :(得分:1)

import pandas as pd
data={'number':['+9185600XXXXX','+9199651XXXXX']}
f=pd.DataFrame(data)
f['number']=f['number'].str.replace('\+91','')
print(f)
相关问题