【问题标题】:Create ID with information based on dict keys使用基于字典键的信息创建 ID
【发布时间】:2023-02-20 18:47:53
【问题描述】:

我有一个包含以下输入的大型数据框

client type country potential
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

我想为每个客户创建一个 ID。 身份证应该不是随机的(我尝试使用 uuid 包)但包含有关客户端和具有相同属性的单独客户端的信息。

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 client type country potential
A-1-1-1 Client 1 Private USA low
A-3-3-1 Client 2 Private Ireland high
B-2-2-1 Client 3 Institutional GB mid
B-2-2-2 Client 4 Institutional GB mid
B-2-2-3 Client 5 Institutional GB mid

提前致谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用:

    # reorganize your mapping dictionary
    # to have the key: value in correct order
    mapper = {k1: {k: v for v, k in d.items()}
              for k1, d in ID_classification.items()}
    
    # map all desired columns
    df['id'] = df[list(mapper)].apply(lambda s: s.map(mapper[s.name])).agg('-'.join, axis=1)
    
    # add unique id
    df['id'] += '-' + df.groupby('id').cumcount().add(1).astype(str)
    

    输出:

         client           type  country potential       id
    0  Client 1        Private      USA       low  A-1-1-1
    1  Client 2        Private  Ireland      high  A-3-3-1
    2  Client 3  Institutional       GB       mid  B-2-2-1
    3  Client 4  Institutional       GB       mid  B-2-2-2
    4  Client 5  Institutional       GB       mid  B-2-2-3
    

    【讨论】:

      【解决方案2】:

      使用:

      #swap key value in inner dictionaries
      d = {k:{v1:k1 for k1, v1 in v.items()} for k, v in ID_classification.items()}
      
      #map columns by d with join together by -
      s = pd.DataFrame([df[k].map(v) for k, v in d.items()]).agg('-'.join)
      
      #added counter column by Series s
      df['id'] = s + '-' + df.groupby(s).cumcount().add(1).astype(str)
      print (df)
           client           type  country potential       id
      0  Client 1        Private      USA       low  A-1-1-1
      1  Client 2        Private  Ireland      high  A-3-3-1
      2  Client 3  Institutional       GB       mid  B-2-2-1
      3  Client 4  Institutional       GB       mid  B-2-2-2
      4  Client 5  Institutional       GB       mid  B-2-2-3
      

      【讨论】:

        猜你喜欢
        • 2018-09-10
        • 2021-07-20
        • 2020-04-06
        • 2018-10-07
        • 2020-07-18
        • 2019-11-17
        • 2019-06-14
        • 2021-01-15
        • 1970-01-01
        相关资源
        最近更新 更多