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

Pandas如何按条件删除DataFrame中含-或_的ids字段内容

解决方案

核心实现逻辑:将ids列的字符串按逗号拆分为独立子项,过滤掉所有包含-或_的子项后,再用逗号拼接回字符串即可,无需手动枚举要删除的条目。

方案1:拆分过滤法(可读性高)

逻辑清晰易调整,适合中小数据量场景:

import pandas as pd

df['ids'] = df['ids'].str.split(',').apply(
    lambda x: ','.join([item.strip() for item in x if '-' not in item and '_' not in item])
)

方案2:正则向量化法(性能更高)

基于pandas原生向量化操作实现,无需逐行遍历,适合百万级以上的大体积DataFrame:

import pandas as pd

# 匹配所有包含-或_的子项及相邻逗号
pattern = r'(\b[^,]*[-_][^,]*\b,?)'
df['ids'] = df['ids'].str.replace(pattern, '', regex=True).str.strip(',')

效果验证

用示例数据测试:

# 构造测试数据
data = {'ids': ['cat-1,paws', 'dog-2,paws', 'bird-1,feathers,fish', 'cows-2,bird_3']}
df = pd.DataFrame(data)
# 处理后输出
print(df)

输出结果完全符合预期:

ids
0          paws
1          paws
2  feathers,fish
3              

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:24:05