【问题标题】:Dataframe to dictionary merging keys in python [duplicate]数据框到python中的字典合并键[重复]
【发布时间】:2022-01-15 22:44:42
【问题描述】:

我有一个数据框,如下所示:

一些pro1 有不同的pro2

我想将此数据框转换为字典:

bundles = {
    '12345' : ['a1','b1','c1','e1'],
    '56789' : ['a1'],
    '98765' : ['b1','d1']
}

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    您可以在pro1groupby 并从pro2 创建一个列表,最后转换为字典:

    out = df.groupby('pro1')['pro2'].agg(list).to_dict()
    

    【讨论】:

    • 根据我运行的一些基准测试,apply 实际上只比agg 快一点点。
    • @Atakan 你为什么接受这个答案?我的实际上快一点。
    【解决方案2】:
    bundles = df.groupby('pro1')['pro2'].apply(list).to_dict()
    

    输出:

    >>> bundles
    {
        '12345': ['a1', 'b1', 'c1', 'e1'],
        '56789': ['a1'],
        '98765': ['b1', 'd1']
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 2022-01-17
      相关资源
      最近更新 更多