【问题标题】:how to replace +xx in pandas str replace如何在熊猫str替换中替换+xx
【发布时间】:2019-02-22 08:22:57
【问题描述】:

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

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

sre_constants.error: nothing to repeat

完整的跟踪,

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

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

错误发生在,

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

【问题讨论】:

  • 通过regex=False ?例如:.str.replace('+91','', regex=False)

标签: python pandas


【解决方案1】:

您可以转义特殊的正则表达式值+ (one or more repetitions),例如:

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

或者使用参数regex=False:

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

【讨论】:

    【解决方案2】:
    import pandas as pd
    data={'number':['+9185600XXXXX','+9199651XXXXX']}
    f=pd.DataFrame(data)
    f['number']=f['number'].str.replace('\+91','')
    print(f)
    

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多