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

Pandas基于条件补全DataFrame缺失merchant_type编码的方法

实现方案

核心思路

  • 先将df2转为merchant_type_desc到merchant_type的映射字典,提升匹配效率
  • 对df1的merchant_type列做条件赋值:
    1. 当merchant_type_desc等于NEW MCC CODE时,直接保留原有merchant_type值
    2. 其余场景下,仅填充原有merchant_type的缺失值,非空原值保留,缺失值通过映射字典匹配merchant_type_desc对应编码补全

代码实现

import pandas as pd
import numpy as np

# ---------------------- 示例数据构造 ----------------------
# 待补全的df1
df1 = pd.DataFrame({
    'merchant_id': [1,2,3,4,5],
    'merchant_type': [np.nan, '0001', np.nan, '9998', '9999'],
    'merchant_type_desc': ['餐饮', 'NEW MCC CODE', '超市', 'NEW MCC CODE', 'NEW MCC CODE']
})

# 编码-描述映射表df2
df2 = pd.DataFrame({
    'merchant_type': ['5812', '5411'],
    'merchant_type_desc': ['餐饮', '超市']
})
# ---------------------- 核心处理逻辑 ----------------------
# 1. 构造描述到编码的映射字典
desc_to_code = df2.set_index('merchant_type_desc')['merchant_type'].to_dict()

# 2. 条件填充编码
df1['merchant_type'] = np.where(
    df1['merchant_type_desc'] == 'NEW MCC CODE',
    df1['merchant_type'],
    df1['merchant_type'].fillna(df1['merchant_type_desc'].map(desc_to_code))
)

结果验证

处理后df1输出如下:
| merchant_id | merchant_type | merchant_type_desc |
| --- | --- | --- |
| 1 | 5812 | 餐饮 |
| 2 | 0001 | NEW MCC CODE |
| 3 | 5411 | 超市 |
| 4 | 9998 | NEW MCC CODE |
| 5 | 9999 | NEW MCC CODE |

注意事项

  • 如果df2中存在同一个merchant_type_desc对应多个编码的情况,构造映射字典时会默认保留最后出现的编码,可提前对df2按业务规则去重避免冲突
  • 若df1中存在merchant_type_desc不在df2映射表、且不属于NEW MCC CODE的场景,填充后该位置仍会保留空值,可根据需求追加兜底赋值逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:27:06