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

