pandas多列未知条件场景下匹配维修订单与合格维修厂的实现方法
动态条件下的订单与维修厂匹配解决方案
核心思路
不需要嵌套循环,先动态提取维修厂表(rp)的所有判定条件列,再批量生成匹配掩码即可实现通用逻辑。
实现方法
方法1:逐单匹配(适合小数据量,逻辑直观)
- 首先自动识别rp中的所有条件列,排除id、Type这类不需要匹配的非条件字段即可,无论rp有多少个条件列都可以自适应获取。
- 遍历每个订单时,对所有条件列统一生成「条件为空 或 与订单值相等」的布尔判断,合并所有判断结果筛选出符合要求的维修厂。
示例代码:
# 自动提取rp的所有条件列(按需调整排除的非条件字段即可) cond_cols = [col for col in rp.columns if col not in ("id", "Type")] # 遍历所有订单 for order_id, order_info in o.iterrows(): # 生成匹配掩码:每个条件列满足「为空/和订单对应值相等」,所有列都满足则匹配成功 match_mask = (rp[cond_cols].isna() | (rp[cond_cols] == order_info[cond_cols])).all(axis=1) matched_plants = rp[match_mask] # 输出结果 print(f"订单{order_id}匹配的维修厂:") print(matched_plants) print("-"*30)
方法2:全量向量化匹配(适合大数据量,性能更优)
如果订单和维修厂的数量都比较大,可以用笛卡尔积合并后一次性筛选,完全避免循环,性能提升非常明显。
示例代码:
import pandas as pd # 新增临时键用于生成笛卡尔积 o["tmp_join_key"] = 1 rp["tmp_join_key"] = 1 # 全量合并订单和维修厂 full_comb = o.merge(rp, on="tmp_join_key", suffixes=("_order", "_plant")).drop("tmp_join_key", axis=1) # 提取条件列,生成匹配掩码 cond_cols = [col for col in rp.columns if col not in ("id", "Type", "tmp_join_key")] order_cond_cols = [f"{col}_order" for col in cond_cols] plant_cond_cols = [f"{col}_plant" for col in cond_cols] # 两种满足条件:维修厂对应条件为空,或者值和订单相等 match_mask = (full_comb[plant_cond_cols].isna() | (full_comb[order_cond_cols].values == full_comb[plant_cond_cols].values)).all(axis=1) all_matched = full_comb[match_mask] # 按订单分组获取每个订单的匹配结果 order_matched_result = all_matched.groupby("id_order").apply( lambda x: x[[col for col in rp.columns if col != "tmp_join_key"]].reset_index(drop=True) )
内容的提问来源于stack exchange,提问作者Jan T.
相关产品推荐
相关产品推荐

