如何使用Pandas筛选两列中任一包含指定关键词的行?
多列关键词筛选解决方案
你可以通过**逻辑或运算符(|)**将两列的筛选条件组合,实现「Title或Description包含指定关键词」的需求。
完整代码示例
import pandas as pd # 构建你的DataFrame data = { "Title": ["Area 51", "Matrix", "Spaceballs"], "Description": [ "Aliens come to earth on the 4th of July.", "Hacker Neo discovers the shocking truth.", "A star-pilot for hire and his trusty sidekick must come to the rescue of a princess." ] } df = pd.DataFrame(data) words_of_interest = ["Space", "Aliens"] pattern = "|".join(words_of_interest) # 组合筛选条件:Title含关键词 或 Description含关键词 filtered_df = df[df["Title"].str.contains(pattern) | df["Description"].str.contains(pattern)] print(filtered_df)
代码说明
- 先将关键词用
|拼接成正则匹配模式,让str.contains可以匹配任意一个目标关键词。 - 用
|连接两列的筛选结果,只要某行的任意一列满足条件,就会被保留。 - 如果需要忽略大小写(比如匹配小写的"space"或"aliens"),给
str.contains添加case=False参数即可:filtered_df = df[ df["Title"].str.contains(pattern, case=False) | df["Description"].str.contains(pattern, case=False) ]
输出结果
运行代码后会得到符合条件的两行:
Title Description 0 Area 51 Aliens come to earth on the 4th of July. 2 Spaceballs A star-pilot for hire and his trusty sidekick must ...
内容的提问来源于stack exchange,提问作者magladde
相关产品推荐
相关产品推荐

