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

如何基于另一DataFrame的两列匹配值快速提取DataFrame行?

高效匹配两DataFrame行的方法

你的双重循环方法时间复杂度为O(n*m),在df_master数据量大时效率极低,推荐以下几种高效实现方式:

方法1:使用merge(最推荐)

利用pandas的merge函数按指定列做内连接,这是pandas处理这类匹配场景的最优方案,底层为向量化操作,效率远超循环:

import pandas as pd

# 按两列匹配,仅保留df_master中匹配的行,自动保留所有100多列
df_new = pd.merge(df_master, df_lookup, left_on=['col1', 'col2'], right_on=['col 1', 'col 2'], how='inner')
# 若不需要df_lookup的列,可直接删除
df_new = df_new.drop(columns=['col 1', 'col 2'])

如果df_lookup的列名与df_master完全一致(比如均为col1、col2),可简化为:

df_new = pd.merge(df_master, df_lookup, on=['col1', 'col2'], how='inner')

方法2:使用isin结合元组

将两列组合成元组序列,通过isin快速筛选匹配行:

# 把df_lookup的两列转换为元组集合
lookup_pairs = set(zip(df_lookup['col 1'], df_lookup['col 2']))
# 筛选df_master中两列组合在集合内的行
master_pairs = df_master[['col1', 'col2']].apply(tuple, axis=1)
df_new = df_master[master_pairs.isin(lookup_pairs)]

方法3:使用query(适合少量匹配对)

若df_lookup行数不多,可生成查询字符串筛选:

# 拼接匹配条件,格式为"(col1 == val1 and col2 == val2) or ..."
conditions = ' or '.join([f"(col1 == '{row['col 1']}' and col2 == '{row['col 2']}')" for _, row in df_lookup.iterrows()])
df_new = df_master.query(conditions)

注意:若列值包含单引号等特殊字符需额外处理,且df_lookup行数较多时,该方法效率不如merge。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:05:18