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
相关产品推荐
相关产品推荐

