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

如何在Left Join中忽略默认值,将df1的cat列0视为通配符?

Pandas左连接时将指定列值视为通配符的实现方法

要实现把df1中cat列的0当作通配符(合并时忽略该值,仅匹配type列,且包含df2中所有匹配type的行),不能直接用普通的pd.merge(df1, df2, how='left'),可以按以下步骤操作:

步骤1:拆分df1

把df1拆成两部分:cat为0的行(需要用通配符匹配)和cat不为0的行(正常匹配)。对通配符行,直接去掉cat列,避免后续合并时匹配该列:

import pandas as pd

# 拆分df1
df1_wildcard = df1[df1['cat'] == 0].drop('cat', axis=1)
df1_normal = df1[df1['cat'] != 0]

步骤2:分别执行合并

  • 对正常匹配的行,按cat和type两列做左连接:
result_normal = pd.merge(df1_normal, df2, on=['cat', 'type'], how='left')
  • 对通配符行,只按type列做左连接,这样每个通配符行都会匹配df2中对应type的所有行:
result_wildcard = pd.merge(df1_wildcard, df2, on='type', how='left')

步骤3:合并结果

把两部分合并的结果拼接起来,重置索引即可得到最终结果:

final_result = pd.concat([result_normal, result_wildcard], ignore_index=True)

示例验证

假设我们有以下样例数据:

df1:

typecatvalue1
A1x
B0y
A0z

df2:

typecatvalue2
A1p
A2q
B1r
B2s

执行上述代码后,最终结果会包含:

  • 正常匹配的行:type=A, cat=1对应df2的value2=p
  • 通配符行type=B, value1=y匹配df2中所有type=B的行(cat=1和cat=2)
  • 通配符行type=A, value1=z匹配df2中所有type=A的行(cat=1和cat=2)

最终输出如下:

typecatvalue1value2
A1xp
B1yr
B2ys
A1zp
A2zq

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:32:33