You need to enable JavaScript to run this app. 使用列表推导式实现Pandas DataFrame多条件数据筛选的方法
优惠活动
大模型
产品
解决方案
定价
更多

使用列表推导式实现Pandas DataFrame多条件数据筛选的方法

基于列表推导式的DataFrame多条件筛选实现

前置准备

首先导入pandas并构造示例DataFrame:

import pandas as pd

# 构造示例数据
data = {
    "t": ["2012-03-01 00:00:00", "2012-03-01 00:00:10", "2012-03-01 00:00:20", 
          "2012-03-01 00:00:30", "2012-03-01 00:00:40", "2012-03-01 00:00:50",
          "2012-03-01 01:00:00", "2012-03-01 00:00:10"],
    "a": [100, 200, 500, 600, 50, 70, 1000, 2100],
    "b": [2, 5.6, 6.2, 7.0, 3.2, 12.12, 15.14, 4.9]
}
df = pd.DataFrame(data)

列表推导式筛选实现

核心逻辑是遍历DataFrame每一行,判断是否同时满足两个筛选条件,生成布尔值列表作为索引掩码,最终用掩码提取符合要求的行:

# 列表推导式生成筛选掩码
filter_mask = [ (100 < row.a < 2000) and (row.b > 5) for _, row in df.iterrows() ]
# 索引原表得到结果
new_df = df[filter_mask]

结果验证

打印new_df即可得到预期输出:

t     a      b
1  2012-03-01 00:00:10   200   5.60
2  2012-03-01 00:00:20   500   6.20
3  2012-03-01 00:00:30   600   7.00
6  2012-03-01 01:00:00  1000  15.14

补充说明

如果不是必须使用列表推导式,更推荐pandas原生布尔索引写法,处理大数据量时性能更高:

new_df = df[(df["a"] > 100) & (df["a"] < 2000) & (df["b"] > 5)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 10:36:00