【问题标题】:Creating a dictionary for each customer number in a dataframe为数据框中的每个客户编号创建字典
【发布时间】:2016-05-27 04:38:31
【问题描述】:

我有以下客户互动数据

customer  interacted  
c1           i1  
c1           i2  
c1           i1  
c2           i3  
c2           i1

我想将此数据框转换为另一个数据框,其中一列为客户,第二列为存储交互历史的字典。

第二个df应该像

customer   interhist

    c1     {'i1': 2, 'i2': 1}  
    c2     {'i3':1, 'i1':1}

【问题讨论】:

    标签: python python-2.7 dictionary dataframe


    【解决方案1】:

    collections 模块中的 defaultdictCounter 类对于此类问题非常有用。您可以尝试以下方法:

    from collections import defaultdict, Counter
    
    data_map = defaultdict(Counter)
    for line in your_data_source:
        customer, interacted = line.split()
        data_map[customer][interacted] += 1
    

    这将为您提供一个字典,将客户映射到另一个字典,将他们的交互映射到一个整数。

    【讨论】:

      猜你喜欢
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2023-01-12
      • 2022-09-28
      • 2016-01-14
      相关资源
      最近更新 更多