【问题标题】:assign stores to customers based on the store id in python根据python中的商店ID将商店分配给客户
【发布时间】:2020-08-08 07:34:35
【问题描述】:

请建议,我正在尝试根据客户的 ID 将客户映射到商店,我想映射可以为该客户建议的商店

客户输入数据:

Place u_ID 
NE     NE01
NY     NY02
NJ     NJ09

存储输入数据:

Place u_ID    store_name
NE     NE01        test1
NE     NE01        test23
NE     NE02        test2
NE     NE05        test3
NE     NE05        test5
NY     NY02        test
NY     NE01        Eg
NJ     NJ09         tt

我使用的代码:

cus_el= '+'.join(cus_list) if len(cus_list)>1 else cus_list
cus_el=[cus_el] if len(cus_list)>1 else cus_el

store_el= '+'.join(store_list) if len(store_list)>1 else store_list
store_el=[store_el] if len(store_list)>1 else store_el

writer.writerow([place,store_el+cus_el)

但这给了我

Place     u_ID               store_name   
NE     NE01+NE02+NE05        test1+test23+test5+test2+test3        
NY     NY02+NE01              test+Eg               
NJ     NJ09                    tt

预期输出

Place u_ID    store_name1   store_name2    store_name2
NE     NE01        test1     test23            test5
       NE02        test2
       NE05        test3
NY     NY02        test
       NE01         Eg
NJ     NJ09         tt        

【问题讨论】:

    标签: python python-3.x pandas numpy


    【解决方案1】:

    我无法发表评论,所以我在这里给出我的提示。

    我认为您可以使用 pandas groupby 函数解决问题的第一部分。

    前:

    # importing pandas as pd 
    import pandas as pd     
    
    # First grouping based on "Place" 
    # Within each team we are grouping based on "u_ID" 
    gkk = df.groupby(['Place', 'u_ID']) 
    # Print the first value in each group 
    gkk.first() 
    

    至于商店#列的创建你可以使用你的部分功能。

    【讨论】:

      【解决方案2】:

      应该这样做

      import pandas as pd
      
      df = pd.DataFrame({'Place':['NE', 'NE', 'NE', 'NE', 'NE', 'NE', 'NY', 'NY', 'NJ'],
                         'u_ID':['NE01', 'NE01', 'NE01','NE02', 'NE05', 'NE05', 'NY02', 'NY01', 'NJ09'],
                         'store_name':['test1', 'test23', 'test5','test2', 'test3', 'test5', 'test', 'Eg', 'tt']}) # example dataframe
      
      df['key'] = 1
      df['key'] = 'store_name' + df.groupby(['u_ID', 'Place'])['key'].transform('cumsum').astype(str) # create column of the form store_nameX where X incidates the Xth store
      
      df = df.set_index(['Place', 'u_ID', 'key']).unstack() # transpose
      
      df.columns = list(df.columns.droplevel(0))
      
      df
      

      【讨论】:

        猜你喜欢
        • 2017-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-27
        • 1970-01-01
        • 1970-01-01
        • 2019-05-05
        相关资源
        最近更新 更多