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

如何基于OR条件合并Pandas DataFrame(col_1或col_2匹配col_3)

基于OR条件合并两个DataFrame的单步方案
  • 需求说明:将包含col_1、col_2的df_a,与包含col_3的df_b,基于col_1 == col_3 或 col_2 == col_3的OR条件合并,且无需分两次执行merge操作。

方案一:利用merge(how='cross') + query(Pandas 1.2.0及以上版本)

直接通过交叉合并生成笛卡尔积,再筛选符合OR条件的行,一步完成:

import pandas as pd

# 示例数据
df_a = pd.DataFrame({'col_1': [1, 2, 3], 'col_2': [4, 5, 6]})
df_b = pd.DataFrame({'col_3': [2, 5, 7]})

# 单步合并并筛选
merged_df = df_a.merge(df_b, how='cross').query('col_1 == col_3 or col_2 == col_3')

方案二:手动构造交叉连接(兼容低版本Pandas)

给两个DataFrame添加临时键实现交叉合并,再过滤条件并删除临时键:

import pandas as pd

# 示例数据
df_a = pd.DataFrame({'col_1': [1, 2, 3], 'col_2': [4, 5, 6]})
df_b = pd.DataFrame({'col_3': [2, 5, 7]})

# 添加临时键并合并筛选
df_a['temp_key'] = 1
df_b['temp_key'] = 1
merged_df = df_a.merge(df_b, on='temp_key').query('col_1 == col_3 or col_2 == col_3').drop('temp_key', axis=1)

两种方案均无需拆分两次merge操作,直接通过交叉合并后过滤的方式实现OR条件的合并逻辑,避免了重复合并后去重的额外步骤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:15:38