【问题标题】:Pandas dataframe to dictionary of lists熊猫数据框到列表字典
【发布时间】:2020-07-22 22:41:27
【问题描述】:

具有以下形式的数据框:

element1   | element2  |  element3
cat           bird          plane
dog           poodle        cloud
pig           bike          sky

我想将其转换为表单列表的字典

{ 'element1' : ['cat', 'dog', 'pig'], 
  'element2' : ['bird', 'poodle', 'bike'],
  'element3' : ['plane', 'cloud', 'sky']  }

我正在查看.to_dict 方法的documentation,但似乎没有一个选项能满足我的需要。

【问题讨论】:

标签: python pandas dataframe dictionary


【解决方案1】:

使用DataFrame.to_dictlist 参数:

d = df.to_dict('list')
print (d)
{'element1': ['cat', 'dog', 'pig'],
 'element2': ['bird', 'poodle', 'bike'], 
 'element3': ['plane', 'cloud', 'sky']}

【讨论】:

    【解决方案2】:

    通常 to_dict 基于索引元素作为键值,因此转置您的数据框并逐行应用列表,然后进行字典转换

    df.T.apply(list,1).to_dict()
    

    输出:

    {'element1': ['cat', 'dog', 'pig'],
     'element2': ['bird', 'poodle', 'bike'],
     'element3': ['plane', 'cloud', 'sky']}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-17
      • 2017-08-02
      • 2017-02-27
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 2019-08-24
      相关资源
      最近更新 更多