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

如何在Pandas中实现基于分类值的条件过滤(指定食材保留特定菜品)

如何在Pandas中实现基于分类值的条件过滤(指定食材保留特定菜品)

嘿,这个需求用Pandas的布尔索引就能轻松搞定,我给你分享两种常用的实现方式,你可以根据自己的习惯来选~

首先先还原你的原始数据:

IndexIngredientDish
1PotatoPie
2PotatoJuice
3PotatoFries
4PotatoPure
5ApplePie
6AppleJuice
7AppleFries
8ApplePure

你的核心需求是:当Ingredient为Apple时,只保留Dish为Pie和Juice的行;而Potato对应的所有行都完整保留。

方法一:布尔索引组合条件

这是最基础也最灵活的写法,通过逻辑运算符把两个条件组合起来:

import pandas as pd

# 构造原始DataFrame
data = {
    'Index': [1,2,3,4,5,6,7,8],
    'Ingredient': ['Potato']*4 + ['Apple']*4,
    'Dish': ['Pie','Juice','Fries','Pure']*2
}
df = pd.DataFrame(data)

# 应用过滤条件
filtered_df = df[
    # 保留所有非Apple的行
    (df['Ingredient'] != 'Apple') | 
    # 只保留Apple中Dish在指定列表的行
    (df['Dish'].isin(['Pie', 'Juice']))
]

print(filtered_df)

逻辑解释:|代表“逻辑或”,只要满足两个条件中的任意一个就会被保留——要么食材不是Apple(所有Potato行都留),要么是Apple且菜品在指定列表里(只留符合的Apple行)。

方法二:使用query方法(更简洁)

如果喜欢更直观的类SQL语法,Pandas的query方法会更顺手:

filtered_df = df.query("Ingredient != 'Apple' or Dish in ['Pie', 'Juice']")

这个写法和方法一的逻辑完全一致,但代码更紧凑,可读性也不错。

最终结果

运行后得到的结果就是你想要的:

IndexIngredientDish
1PotatoPie
2PotatoJuice
3PotatoFries
4PotatoPure
5ApplePie
6AppleJuice

备注:内容来源于stack exchange,提问作者MaximJ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 18:13:08