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

如何在pandas中使用字典基于多列匹配规则过滤DataFrame数据

实现方案

你可以根据数据集大小选择以下两种方案,规则更新只需修改code字典即可,无需调整过滤逻辑:

方案1:直观行匹配(适合万行以下小数据集)

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({
    'file': ['90.txt', '90.txt', '60.txt', '60.txt', '90.txt', '50.txt', '80.txt', '100.txt'],
    'Voucher_stand': ['SCA', 'SCB', 'WFA', 'WFO', 'SCA', 'SCA', 'SCA', 'SCA']
})

# 过滤规则字典
code = {'90.txt':['SCA', 'SCB'], '60.txt':['WFA', 'WFO']}

# 核心过滤逻辑
df_filtered = df[df.apply(lambda x: x['Voucher_stand'] in code.get(x['file'], []), axis=1)]

运行后得到的df_filtered会保留所有符合规则的行,示例场景下会输出90.txt和60.txt对应的5条有效数据,其余不在规则内的file对应行直接过滤。

方案2:向量化运算(适合十万行以上大数据集,性能远高于行遍历)

# 生成匹配掩码
mask = pd.Series(False, index=df.index)
for file, valid_values in code.items():
    mask |= (df['file'] == file) & df['Voucher_stand'].isin(valid_values)

# 过滤数据
df_filtered = df[mask]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:45:03