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

如何检查pandas DataFrame单行是否同时匹配多个条件读取指定CSV文件

解决方案

你原来的isin逻辑会逐列单独匹配值,只要三个列分别有命中就返回True,无法实现「某一行同时匹配三个参数」的要求,可按以下方案修正:

方案1:直接多条件匹配(适合清单数据量小的场景)

直接构造三列同时匹配的过滤条件,判断过滤结果是否非空即可:

import os
import pandas as pd

for root, dirs, files in os.walk(CollectionDirectory, topdown=False):
    for File in files:
        # 先拆分文件名去掉后缀,避免后缀干扰参数提取
        file_name_no_ext = os.path.splitext(File)[0]
        name_parts = file_name_no_ext.split("_")
        Energy = int(name_parts[-3])
        Potential = name_parts[-2]
        Try = int(name_parts[-1])
        # 判断是否存在整行同时匹配的记录
        if not checklistDf[(checklistDf['Energy'] == Energy) & (checklistDf['Potential'] == Potential) & (checklistDf['Try'] == Try)].empty:
            # 注意拼接完整路径,避免子目录下文件找不到
            DfNew = pd.read_csv(os.path.join(root, File))
            # 后续可自行添加DfNew的处理逻辑

方案2:预转元组集合(适合文件数量多、清单量大的场景,效率更高)

提前把清单的三列组合成元组存入集合,匹配时直接判断元组是否在集合中即可,时间复杂度为O(1):

import os
import pandas as pd

# 提前预处理清单,生成有效组合的集合
valid_combinations = set(checklistDf[['Energy', 'Potential', 'Try']].itertuples(index=False, name=None))

for root, dirs, files in os.walk(CollectionDirectory, topdown=False):
    for File in files:
        file_name_no_ext = os.path.splitext(File)[0]
        name_parts = file_name_no_ext.split("_")
        current_tuple = (int(name_parts[-3]), name_parts[-2], int(name_parts[-1]))
        if current_tuple in valid_combinations:
            DfNew = pd.read_csv(os.path.join(root, File))
            # 后续可自行添加DfNew的处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:24:05