Python Pandas 匹配列值存所属组名 解决lambda赋值覆盖问题
问题根因说明
你之前的写法存在两个核心bug,导致结果完全不符合预期:
- 列值被连续覆盖:每一次对
df1_1['GMPL']赋值,都是将整列的计算结果完全替换,不是在上一次计算的基础上更新标注。举个例子:某产品值属于automotive分组,第一行赋值时会被标成'automotive';但执行第二行判断home的赋值时,因为这个值不在home列表里,lambda会返回原始产品值,把之前标好的'automotive'直接覆盖掉。最终整列只会保留最后一次(判断timing分组)的计算结果,前面所有分组的标注都会被冲掉。 - 判断逻辑不闭环:你写的lambda逻辑为「匹配到当前列表就返回分组名,否则返回原始产品值」,就算不发生列覆盖,最终列内的值也会混杂分组名和原始产品名,无法形成标准化的分组标注。
正确实现方案
第一步:构建统一的分组映射字典
先把所有零散的预定义列表整理成「具体产品项: 所属分组名称」的映射关系,避免重复写十几次判断逻辑:
# 初始化空的映射字典 group_map = {} # 依次将每个预定义列表的内容写入映射关系 group_map.update({item: "automotive" for item in automotive}) group_map.update({item: "home" for item in home}) group_map.update({item: "b8_mcu" for item in b8_mcu}) group_map.update({item: "iot15_4" for item in iot15_4}) group_map.update({item: "b32_mcu" for item in b32_mcu}) group_map.update({item: "bluetooth" for item in bluetooth}) group_map.update({item: "proprietary" for item in proprietary}) group_map.update({item: "sensors" for item in sensors}) group_map.update({item: "touch" for item in touch}) group_map.update({item: "wifi" for item in wifi}) group_map.update({item: "zwave" for item in zwave}) group_map.update({item: "access" for item in access}) group_map.update({item: "power" for item in power}) group_map.update({item: "timing" for item in timing})
第二步:生成GMPL分组列并完成校验
用映射字典直接匹配产品所属分组,同时对不在预定义列表的项做兜底标记,同时满足两项核心需求:
# 匹配产品所属分组,未命中预定义列表的项标记为"未匹配" df1_1["GMPL"] = df1_1["Product Line"].map(group_map).fillna("未匹配") # 提取所有未匹配的产品值,完成预定义列表覆盖度校验 unmatched_products = df1_1[df1_1["GMPL"] == "未匹配"]["Product Line"].unique()
优势:相比连续写lambda判断的方式,这种写法计算效率更高,后续如果需要调整分组列表,只需要修改初始的列表定义,不需要改动后续的分组计算逻辑。
内容的提问来源于stack exchange,提问作者Alex Günsberg
相关产品推荐
相关产品推荐

