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

Python Pandas:如何实现pandas.Series.str.match的反向匹配效果

Pandas 反向匹配字符串开头规则实现方案

pandas.Series.str.match 默认从字符串起始位置匹配正则规则,返回匹配成功为True、失败为False的布尔序列,你需要的反向结果直接通过波浪号(~)取反运算符即可实现。

示例代码

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({
    'content': ['123_abc', 'test_456', '789_def', 'hello_world', '_special']
})

# 自定义正则规则:示例为匹配以数字开头的字符串
pattern = r'^\d'

# 得到【不符合匹配规则返回True】的结果序列
not_match_flag = ~df['content'].str.match(pattern)

运行后not_match_flag输出结果如下:

0    False
1     True
2    False
3     True
4     True
Name: content, dtype: bool

注意事项

  • 若目标列存在NaN空值,str.match默认对空值返回NaN,取反后仍然为NaN。你可以通过na参数指定空值的匹配结果:
    • 空值统一判定为不符合规则(返回False):~df['content'].str.match(pattern, na=False)
    • 空值统一判定为符合规则(返回True):~df['content'].str.match(pattern, na=True)
  • 也可以直接修改正则表达式,用负向前瞻规则实现相同效果,无需额外取反,示例:
    not_match_flag = df['content'].str.match(r'^(?!\d)')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:54:02