【问题标题】:Convert a Pandas DataFrame to a dictionary with values of same class together将 Pandas DataFrame 转换为具有相同类值的字典
【发布时间】:2020-08-17 18:01:45
【问题描述】:

我有一个包含两列的 DataFrame。我想将此 DataFrame 转换为 python 字典。我希望第一列的元素是键,而另一列的元素是值。

   item_cat_id  item_id
0            0       12
1            2       11
2            1       13
3            3       20
4            1       22
5            1       19
6            2       15
7            0       25

我希望我的输出作为字典:

{'0': [12,25], '1': [13,22,19], '2': [11,15], '3' : [20]}

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:
    df.groupby('item_cat_id')['item_id'].apply(list).to_dict()
    

    样本数据:

        Animal  Number_legs
    0   fox         4
    1   Kangaroo    2
    2   deer        4
    3   spider      8
    4   fox         7
    

    代码:

    df.groupby('Animal')['Number_legs'].apply(list).to_dict()
    

    结果:

    {'Kangaroo': [2], 'deer': [4], 'fox': [4, 7], 'spider': [8]}
    

    【讨论】:

    • 但是如果我有
    • item_cat_id item_id 0 12 2 11 1 22 3 20 1 22 1 19 2 15 0 12
    • 如果两行的 item_id 相同,item_cat_id 相同,该怎么办
    • @Amit 没问题。我用 fox - 4 替换了上面例子中的袋鼠,结果如下: {'deer': [4], 'fox': [4, 4, 7], 'spider': [8]} But you don'不想要重复的条目,这是一个不同的问题。
    【解决方案2】:

    替代解决方案:

    df.groupby('item_cat_id').item_id.agg(lambda x: list(x)).to_dict()
    

    结果:

    {0: [12, 25], 1: [13, 22, 19], 2: [11, 15], 3: [20]}
    

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2018-07-25
      • 2017-12-26
      • 2014-12-30
      • 2014-06-23
      • 2018-10-26
      • 2013-11-16
      相关资源
      最近更新 更多