【问题标题】:Avoid pandas str.replace using a regex使用正则表达式避免 pandas str.replace
【发布时间】:2016-07-17 18:11:12
【问题描述】:

我有以下熊猫数据框。假设它有两列:idsearch_term

id       search_term
37651    inline switch

我愿意:

train['search_term'] = train['search_term'].str.replace("in."," in. ")

期望上面的数据集不受影响,但我得到了这个数据集的回报:

id       search_term
37651    in.  in.  switch

这意味着inlin. 替换,inein. 替换,就好像我在使用正则表达式时一样,其中点表示任何字符。

我如何重写第一个命令,以便从字面上看,in.in. 替换,但任何后面没有点的 in 都保持不变,如下所示:

a = 'inline switch'
a = a.replace('in.','in. ')

a
>>> 'inline switch'

【问题讨论】:

  • 你实际想要的输出是什么?
  • 对不起,我想从字面上替换“点”。我在下面发布了一个答案,因为我发现了一篇关于“点”正则表达式的好帖子。问题是数据框中的 str.replace() 使用正则表达式

标签: python regex string pandas replace


【解决方案1】:

0.23 或更高版本,str.replace() 获得了切换正则表达式的新选项。 以下将简单地将其关闭。

df.search_term.str.replace('in.', 'in. ', regex=False)

将导致:

0    inline switch
1         in. here
Name: search_term, dtype: object

【讨论】:

    【解决方案2】:

    这就是答案:匹配点的正则表达式。

    str.replace() 在 pandas 中确实使用了正则表达式,所以:

    df['a'] = df['a'].str.replace('in.', ' in. ')
    

    无法与:

    a.replace('in.', ' in. ')
    

    后者不使用正则表达式。所以使用'\。'代替 '。'如果您真的是指点而不是任何字符,则在使用正则表达式的语句中。

    Regular Expression to match a dot

    【讨论】:

    • 但是请注意,您仍然可以使用正则表达式,同时声明点没有特殊含义。
    【解决方案3】:

    尝试转义.

    import pandas as pd
    
    df = pd.DataFrame({'search_term': ['inline switch', 'in.here']})
    >>> df.search_term.str.replace('in\\.', 'in. ')
    0    inline switch
    1          in. here
    Name: search_term, dtype: object
    

    【讨论】:

    • 感谢阿米。我看你逃过了。在第一个论点中,但第二个呢?如果你想从字面上替换'in'。通过'在。 ' 然后你应该使用 str.replace('in\\.', 'in\\.') 还是 str.replace('in\\.', 'in.')?
    • @AlejandroSimkievich 这似乎合乎逻辑,但不是。请参阅上面的更新示例。只有第一个字符串中的点被解释为正则表达式字符(必须转义)。
    猜你喜欢
    • 1970-01-01
    • 2020-02-19
    • 2021-01-04
    • 2021-05-30
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    相关资源
    最近更新 更多