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

如何按字符串开头子串过滤Pandas DataFrame

过滤Pandas DataFrame中指定列不以特定前缀开头的行

要保留DRUG_CODE列以B21开头的行,过滤掉不符合条件的行,有两种高效方法:

方法1:使用str.startswith()(推荐)

这是Pandas专门用于判断字符串前缀的方法,逻辑直观且性能稳定:

# 假设你的DataFrame名为df
filtered_df = df[df['DRUG_CODE'].str.startswith('B21')]

方法2:使用str.contains()配合正则锚点

如果习惯用正则表达式,可以通过^锚点限定匹配字符串开头:

filtered_df = df[df['DRUG_CODE'].str.contains('^B21')]

处理含缺失值的情况

如果DRUG_CODE列存在缺失值(NaN),添加na=False参数避免报错:

# startswith方式
filtered_df = df[df['DRUG_CODE'].str.startswith('B21', na=False)]

# 正则方式
filtered_df = df[df['DRUG_CODE'].str.contains('^B21', na=False)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:17:03