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

Pandas匹配两个DataFrame的ID字段获取所有对应行数据的问题求解

你现有代码的问题是每次循环都会直接覆盖patients变量,所以循环结束后只会保留最后一次匹配到的结果。

最优解决方案:使用向量化匹配(无需循环)

pandas内置的isin()方法支持批量匹配多个ID,执行效率远高于手动循环,代码更简洁:

import pandas as pd

patientSet = pd.read_csv("794_chips_RMA.csv")
affSet = probeset[probeset['Analysis']==1].reset_index(drop=True) 
houseGenes = probeset[probeset['Analysis']==0].reset_index(drop=True)

# 直接筛选ID属于affSet.Probeset的所有行
patients = patientSet[patientSet['ID'].isin(affSet['Probeset'])].reset_index(drop=True)

print(patients)
可选方案:循环实现(仅特殊需求下使用)

如果必须通过循环实现逻辑,可以用列表暂存每次的匹配结果,最后合并为一个DataFrame:

patientSet = pd.read_csv("794_chips_RMA.csv")
affSet = probeset[probeset['Analysis']==1].reset_index(drop=True) 
houseGenes = probeset[probeset['Analysis']==0].reset_index(drop=True)

match_res = []
for x in affSet['Probeset']:
    tmp = patientSet[patientSet['ID']==x].reset_index(drop=True)
    # 跳过无匹配的空结果
    if not tmp.empty:
        match_res.append(tmp)

# 合并所有匹配结果
patients = pd.concat(match_res, ignore_index=True)

print(patients)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 01:15:03