如何在Python Pandas的.loc中实现SQL多条件合并查询逻辑?
Pandas中实现SQL式多字段组合条件过滤
你的核心问题是要把gameId和playId作为组合主键来判断是否排除,而非单独判断每个字段。之前的代码逻辑有误,因为单独字段的isin判断无法代表组合的唯一性,才会导致结果不符合预期或报错。
下面是两种可行的实现方式:
方法1:直接判断字段组合是否在目标集合中
先把brokenplays里的gameId和playId组合成元组集合,再用apply把scout的对应字段转成元组,最后做整体判断:
# 生成brokenplays中需要排除的(gameId, playId)组合 broken_pairs = list(zip(brokenplays['gameId'], brokenplays['playId'])) # 构建完整过滤条件 filter_condition = ( scout['nflId'].isin(OLs.nflId) # 取反:排除组合匹配的行 & ~scout[['gameId', 'playId']].apply(tuple, axis=1).isin(broken_pairs) ) # 应用过滤 filtered_scout = scout.loc[filter_condition]
方法2:用左连接标记后过滤
通过merge左连接scout和brokenplays的组合字段,标记出匹配的行,再过滤掉这些行:
# 左连接,只保留brokenplays的组合字段,添加_merge标记列 scout_joined = scout.merge( brokenplays[['gameId', 'playId']], on=['gameId', 'playId'], how='left', indicator=True ) # 过滤条件:nflId符合要求,且未匹配到brokenplays的行 filtered_scout = scout_joined.loc[ scout_joined['nflId'].isin(OLs.nflId) & (scout_joined['_merge'] == 'left_only') ].drop(columns='_merge') # 移除标记列
为什么原来的代码不对?
你之前的逻辑是gameId不在brokenplays的gameId列表里 并且 playId不在brokenplays的playId列表里,这会错误排除很多不需要排除的行——比如某个gameId在brokenplays里,但对应的playId不在,或者反过来。而我们真正要排除的是**gameId和playId的组合完全匹配brokenplays中某一行**的记录,必须把两个字段作为整体判断。
内容的提问来源于stack exchange,提问作者user11279819
相关产品推荐
相关产品推荐

