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

如何使用for循环在filter函数中过滤DataFrame指定列?

使用for循环实现DataFrame指定列的列表元素过滤

方法1:手动构建布尔过滤条件

先初始化一个全为False的布尔序列,然后遍历目标列表中的每个元素,逐步叠加「或」条件:

import pandas as pd

# 示例DataFrame
df = pd.DataFrame({'col1': ['ca', 'ab', 'hg', 'xy', 'po'], 'col2': [1, 2, 3, 4, 5]})
my_list = ['ca', 'hg', 'po']

# 初始化过滤条件:所有行先标记为不符合
filter_mask = pd.Series([False] * len(df), index=df.index)

# 循环遍历列表元素,更新过滤条件
for item in my_list:
    filter_mask = filter_mask | (df['col1'] == item)

# 应用过滤得到结果
filtered_df = df[filter_mask]

方法2:用reduce简化循环逻辑

借助functools.reduce函数,把循环中的「或」操作封装起来,代码更紧凑:

from functools import reduce
import pandas as pd

df = pd.DataFrame({'col1': ['ca', 'ab', 'hg', 'xy', 'po'], 'col2': [1, 2, 3, 4, 5]})
my_list = ['ca', 'hg', 'po']

# 通过reduce叠加所有元素的匹配条件
filter_mask = reduce(lambda acc, item: acc | (df['col1'] == item), my_list, pd.Series([False]*len(df), index=df.index))

filtered_df = df[filter_mask]

额外提示:更高效的内置方法

其实Pandas原生提供了isin()方法,完全不需要写循环就能实现相同需求,代码更简洁且性能更优:

filtered_df = df[df['col1'].isin(my_list)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:27:36