【问题标题】:why pandas str.replace with .* pattern insers replacement value multiple times [duplicate]为什么pandas str.replace用.*模式多次插入替换值[重复]
【发布时间】:2021-05-27 18:36:05
【问题描述】:

我正在尝试使用 pandas str.replace 函数来替换模式。

但是当我这样做时:

pd.DataFrame({'text_col':['aaa', 'c', 'bbbbb', 'ddd']})['text_col'].str.replace('.*', 'RR')

由于某种原因返回:

0    RRRR
1    RRRR
2    RRRR
3    RRRR
Name: text_col, dtype: object

虽然我会返回相同的结果:

pd.DataFrame({'text_col':['aaa', 'c', 'bbbbb', 'ddd']})['text_col'].str.replace('^.*$', 'RR')

返回:

0    RR
1    RR
2    RR
3    RR
Name: text_col, dtype: object

如果我将此行为与 R 编程语言进行比较,替换模式 .*^.*$ 会产生相同的结果。为什么在 Pandas 中会有所不同?

【问题讨论】:

    标签: python regex pandas replace


    【解决方案1】:

    两种正则表达式模式不同。

    • a* -> 零个或多个 a。

    看看这个例子。

    >>> import re
    >>> re.findall('.*', 'c')
    # ['c', '']
    
    >>> re.findall('.*', 'AAAAAAA')
    # ['AAAAAAA', '']
    
    >>> re.findall('.*', '')
    # [''] 
    
    • '.*' 也匹配空字符串。 _.str.replace 替换每个匹配项,因此您总是得到两个匹配项,即一个是实际字符串,两个是空字符串。所以,你总是会收到'RRRR'

    如果你想匹配一个或匹配字符,你可以使用下面的正则表达式。

    pat = r'.{1, }'
    

    【讨论】:

    • 哦,哇,我没想到它也会匹配非空字符串中的空字符串。我认为 .* 只会匹配整个字符串。
    猜你喜欢
    • 2020-01-09
    • 2020-10-07
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 2018-05-17
    相关资源
    最近更新 更多