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

如何在Python中按多条件筛选DataFrame:指定ID的VALUE为1时提取数据

筛选指定ID且VALUE为1的DataFrame数据

直接用pandas的布尔索引结合isin()方法就能实现需求,步骤如下:

  1. 定义目标ID列表:
target_ids = ['AB0120', 'AB0121', 'AB0122', 'AB0123', 'AB0124', 'AB0125']
  1. 组合两个筛选条件(ID在目标列表中 且 VALUE等于1)进行过滤:
import pandas as pd

# 构造你的DataFrame
data = {
    'Time': ['2022-05-03']*11,
    'EQU': ['202201']*11,
    'ID': ['AB0125', 'AB0120', 'AB0121', 'AB0122', 'AB0123', 'AB0124', 'AB0125', 'DE0112', 'FE0253', 'GE0223', 'WW0365'],
    'VALUE': [0, 0, 0, 1, 0, 0, 0, 120, 23, 50, 10]
}
df = pd.DataFrame(data)

# 执行筛选
filtered_df = df[(df['ID'].isin(target_ids)) & (df['VALUE'] == 1)]
print(filtered_df)

运行后会得到符合条件的唯一一行数据:

Time    EQU       ID  VALUE
3  2022-05-03  202201  AB0122      1

关键说明

  • df['ID'].isin(target_ids):判断每行的ID是否在指定的目标列表中,返回布尔序列
  • &:逻辑与操作,要求两个条件同时满足,注意必须用括号把每个条件单独括起来,避免运算优先级问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:20:28