【问题标题】:How to create a dictionary with the unique value of the column and store the values into list [duplicate]如何使用列的唯一值创建字典并将值存储到列表中[重复]
【发布时间】:2021-04-12 16:28:03
【问题描述】:

我有一个包含以下内容的数据框:

  A   B  
1 Cat 1
2 Cat 2
3 Dog 1
4 Dog 2
5 Dog 3
6 Dog 4

我想用上面的数据框创建一个这样的字典: {'Cat':[1,2], 'Dog':[1,2,3,4]} 任何人都可以对此有所了解吗?谢谢。

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    使用groupby()方法apply()方法to_dict()方法:

    result=df.groupby('A')['B'].apply(list).to_dict()
    

    现在,如果您打印 result,您将获得所需的输出:

    {'Cat': [1, 2], 'Dog': [1, 2, 3, 4]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 2011-11-24
      • 2016-09-29
      相关资源
      最近更新 更多