You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas中str.contains匹配带括号字符串失效问题排查

问题原因与解决方法

为什么str.contains匹配不到目标字符串?

因为pandas.Series.str.contains()默认开启正则表达式模式,你要匹配的字符串里的()是正则中的特殊元字符(用于分组),会被解析成正则语法,而非普通的括号字符,所以无法匹配原字符串里的括号内容,导致匹配失败。

两种解决办法

  • 方法1:关闭正则模式,按字面匹配
    在contains中添加regex=False参数,让方法直接按普通字符串匹配,不解析正则元字符:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame([['Table 1 (not in use after 1 Apr 2023)'], 
                       ['wefwfe'],
                       ['eqv']], 
                      columns=['Venue'])
    
    print(df)
    
    # 添加regex=False,按字面匹配目标字符串
    df['Venue'].loc[df['Venue'].str.contains('Table 1 (not in use after 1 Apr 2023)', regex=False)] = 'Table'
    
    print(df)
    
  • 方法2:转义正则特殊字符
    如果需要保留正则模式(比如后续要做复杂匹配),可以用re.escape()自动转义所有正则特殊字符,把目标字符串转换成安全的正则匹配串:

    import pandas as pd
    import numpy as np
    import re
    
    df = pd.DataFrame([['Table 1 (not in use after 1 Apr 2023)'], 
                       ['wefwfe'],
                       ['eqv']], 
                      columns=['Venue'])
    
    print(df)
    
    # 用re.escape转义所有正则特殊字符
    target_str = 'Table 1 (not in use after 1 Apr 2023)'
    df['Venue'].loc[df['Venue'].str.contains(re.escape(target_str))] = 'Table'
    
    print(df)
    

内容的提问来源于stack exchange,提问作者unclegood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 08:32:07