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

如何移除DataFrame中含指定停用词的整行数据

需求实现:移除包含停用词的DataFrame行

给定数据

停用词列表

stop_w = ["in", "&", "the", "|", "and", "is", "of", "a", "an", "as", "for", "was"]

原始DataFrame

wordsfrequency
the company10
green energy9
founded in8
gases for8
electricity5

需求

移除words列中包含任意一个指定停用词的整行数据。

预期输出

wordsfrequency
green energy9
electricity5

解决方案代码

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'words': ["the company", "green energy", "founded in", "gases for", "electricity"],
    'frequency': [10, 9, 8, 8, 5]
})

stop_w = ["in", "&", "the", "|", "and", "is", "of", "a", "an", "as", "for", "was"]

# 生成匹配完整停用词的正则表达式,避免部分匹配
pattern = r'\b(' + '|'.join(stop_w) + r')\b'

# 筛选不包含任何停用词的行
filtered_df = df[~df['words'].str.contains(pattern, case=False)]

print(filtered_df)

代码说明

  • 正则中的\b用于匹配完整停用词,防止类似"interesting"里的"in"被误判;
  • ~符号实现取反逻辑,保留不含停用词的行;
  • case=False支持忽略大小写匹配,不需要可直接删除该参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:31:36