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

在Pandas中按指定多条件组合筛选DataFrame行

解决DataFrame多条件组合筛选问题

方法1:将目标列转为元组序列后使用isin

把需要匹配的多列数据转换为元组形式的Series,再通过isin判断是否属于条件组合列表,这种方法简洁高效,适合不需要保留条件列表中重复项对应结果的场景。

import pandas as pd

# 构建示例DataFrame
df = pd.DataFrame({
    'fruit': ['apple', 'banana', 'apple', 'apple', 'pineapple', 'mango'],
    'recipe': ['burn', 'fry', 'slice', 'fry', 'fry', 'fry'],
    'size': ['big', 'small', 'big', 'small', 'small', 'small'],
    'price': [100]*6
}, index=[2,3,5,7,11,13])

# 条件组合列表
order = [("apple", "fry", "big"), ("apple", "fry", "big")]

# 筛选逻辑:将指定列转为元组,再匹配条件列表
filtered_df = df[df[['fruit', 'recipe', 'size']].apply(tuple, axis=1).isin(order)]
print(filtered_df)

方法2:通过merge实现(支持保留重复匹配)

如果你的条件组合列表中存在重复项,且需要在结果中对应重复输出匹配到的行,可以将条件列表转为临时DataFrame,再通过merge完成筛选。

import pandas as pd

# 构建示例DataFrame
df = pd.DataFrame({
    'fruit': ['apple', 'banana', 'apple', 'apple', 'pineapple', 'mango'],
    'recipe': ['burn', 'fry', 'slice', 'fry', 'fry', 'fry'],
    'size': ['big', 'small', 'big', 'small', 'small', 'small'],
    'price': [100]*6
}, index=[2,3,5,7,11,13])

# 条件组合列表
order = [("apple", "fry", "big"), ("apple", "fry", "big")]

# 将条件列表转为DataFrame
order_df = pd.DataFrame(order, columns=['fruit', 'recipe', 'size'])
# 合并筛选,right join会保留order中的所有条目
filtered_df = pd.merge(df, order_df, on=['fruit', 'recipe', 'size'], how='right')
print(filtered_df)

说明

  • 方法1的apply(tuple, axis=1)会把每行的指定列打包成元组,让isin可以直接匹配多值组合。
  • 方法2的merge能处理条件列表中的重复项,比如示例中order有两个相同的组合,结果会返回两次匹配到的行(如果原DataFrame存在对应行的话)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:50:32