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

如何基于dataframe1的基因列筛选dataframe2每行中的匹配基因

两个DataFrame基因匹配过滤方案

核心思路

  • 先将dataframe1的gene列转为集合,利用集合O(1)的查找效率提升处理速度,适合基因量大的场景
  • 遍历dataframe2的每一行gene字段,拆分后仅保留存在于上述集合中的基因,再重新拼接为逗号分隔的字符串
  • 可根据需求选择保留无匹配基因的空行,或直接过滤掉该类行

代码实现

首先导入依赖库:

import pandas as pd

第一步:提取dataframe1的基因集合

# 提取所有目标基因转为集合,自动去重
target_gene_set = set(dataframe1['gene'].unique())

第二步:处理dataframe2的基因列

# 生成新列存储过滤后的基因,不覆盖原始数据方便核对
dataframe2['filtered_gene'] = dataframe2['gene'].apply(
    lambda row: ','.join([gene for gene in row.split(',') if gene in target_gene_set])
)

# 可选操作:过滤掉没有匹配到任何基因的行
dataframe2 = dataframe2[dataframe2['filtered_gene'] != ''].reset_index(drop=True)

示例运行结果

按照你给出的示例数据处理后,最终dataframe2['filtered_gene']的结果为:

  • row1:a,b,c,d
  • row2:c,a,b,c

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 12:06:06