【问题标题】:Pandas dataframe to dictionary熊猫数据框到字典
【发布时间】:2016-10-17 13:43:51
【问题描述】:

我有一个像这样的熊猫数据框:

COL1 VALUE1 VALUE2
 A      A12     1    
 B      B13     2 
 A      C12     3
 B      Q12     4

需要来自上述数据帧的字典,其中 COL1 将作为键存储,value1 和 value2 将在子字典中。

例如:-

dict = {'A':{'A12':1, 'C12':3}, B:{'B13':2, 'Q12':4}}

【问题讨论】:

    标签: python dictionary pandas group-by


    【解决方案1】:

    您可以使用groupbyapply 转换为dict ziped 列并最后转换to_dict

    d = df.groupby('COL1').apply(lambda x: dict(zip(x.VALUE1, x.VALUE2))).to_dict()
    print (d)
    {'A': {'C12': 3, 'A12': 1}, 'B': {'B13': 2, 'Q12': 4}}
    

    【讨论】:

      猜你喜欢
      • 2017-08-02
      • 2017-02-27
      • 2020-07-23
      • 1970-01-01
      • 2021-07-17
      • 2020-07-22
      • 2021-10-26
      • 2023-03-23
      • 2018-06-24
      相关资源
      最近更新 更多