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

基于字典映射为DataFrame生成含属性的非随机客户ID需求

问题

现有大型DataFrame数据如下:

客户类型国家潜力
Client 1PrivateUSAlow
Client 2PrivateIrelandhigh
Client 3InstitutionalGBmid
Client 4InstitutionalGBmid
Client 5InstitutionalGBmid

需要为每个客户生成非随机、包含客户信息且能区分属性相同客户的ID,给定分类字典:

ID_classification = {'type':{'A':'Private','B':'Institutional'},
                     'country':{'1':'USA','2':'GB','3':'Ireland'},
                     'potential':{'1':'low','2':'mid','3':'high'}}

ID格式要求为 type.key-country.key-potential.key-unique_id,预期生成结果如下:

id客户类型国家潜力
A-1-1-1Client 1PrivateUSAlow
A-3-3-1Client 2PrivateIrelandhigh
B-2-2-1Client 3InstitutionalGBmid
B-2-2-2Client 4InstitutionalGBmid
B-2-2-3Client 5InstitutionalGBmid

实现方案

步骤1:反转分类字典

原字典是编码对应属性值,我们需要通过属性值反向查询编码,因此先反转每个子字典:

# 反转分类字典,构建属性值到编码的映射
reverse_class = {
    col: {v: k for k, v in mapping.items()} 
    for col, mapping in ID_classification.items()
}

步骤2:用Pandas生成目标ID

利用Pandas的映射、分组计数功能实现需求,代码如下:

import pandas as pd

# 构造示例DataFrame(实际使用中替换为你的原始数据)
data = [
    ["Client 1", "Private", "USA", "low"],
    ["Client 2", "Private", "Ireland", "high"],
    ["Client 3", "Institutional", "GB", "mid"],
    ["Client 4", "Institutional", "GB", "mid"],
    ["Client 5", "Institutional", "GB", "mid"]
]
df = pd.DataFrame(data, columns=["客户", "类型", "国家", "潜力"])

# 1. 为每个属性添加对应编码列
df["type_code"] = df["类型"].map(reverse_class["type"])
df["country_code"] = df["国家"].map(reverse_class["country"])
df["potential_code"] = df["潜力"].map(reverse_class["potential"])

# 2. 生成组内唯一序号:按类型、国家、潜力分组,每组内从1开始递增计数
df["unique_id"] = df.groupby(["类型", "国家", "潜力"]).cumcount() + 1

# 3. 拼接各部分生成最终ID
df["id"] = df.apply(
    lambda row: f"{row['type_code']}-{row['country_code']}-{row['potential_code']}-{row['unique_id']}",
    axis=1
)

# 调整列顺序并输出结果
result_df = df[["id", "客户", "类型", "国家", "潜力"]]
print(result_df)

关键逻辑说明

  • 反转字典:通过字典推导式快速生成值到编码的映射,避免手动编写反向映射的冗余工作。
  • 组内计数:groupby().cumcount() 会对每个属性组合的组内元素从0开始计数,加1后得到从1开始的唯一序号,完美区分属性完全相同的客户。
  • ID拼接:用apply逐行拼接各编码部分,严格匹配要求的格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:15:41