当前位置:首页 » python教程 » 正文

Pandas DataFrame转换为字典的方法

看: 725次  时间:2021-06-18  分类 : python教程

该to_dict()方法将列名设置为字典键将“ID”列设置为索引然后转置DataFrame是实现此目的的一种方法。to_dict()还接受一个'orient'参数,您需要该参数才能输出每列的值列表。否则,{index: value}将为每列返回表单的字典。

可以使用以下行完成这些步骤:

>>> df.set_index('ID').T.to_dict('list')
{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

如果需要不同的字典格式,这里是可能的东方参数的示例。考虑以下简单的DataFrame:

>>> df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
>>> df
        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125

然后选项如下。

dict - 默认值:列名是键,值是索引的字典:数据对

>>> df.to_dict('dict')
{'a': {0: 'red', 1: 'yellow', 2: 'blue'}, 
 'b': {0: 0.5, 1: 0.25, 2: 0.125}}

list - 键是列名,值是列数据列表

>>> df.to_dict('list')
{'a': ['red', 'yellow', 'blue'], 
 'b': [0.5, 0.25, 0.125]}

系列 - 比如'list',但值是Series

>>> df.to_dict('series')

{'a': 0       red
      1    yellow
      2      blue
      Name: a, dtype: object, 
 'b': 0    0.500
      1    0.250
      2    0.125
      Name: b, dtype: float64}

split - 将列/数据/索引拆分为键,值分别为列名,数据值分别按行和索引标签

>>> df.to_dict('split')

{'columns': ['a', 'b'],
 'data': [['red', 0.5], ['yellow', 0.25], ['blue', 0.125]],
 'index': [0, 1, 2]}

记录 - 每一行都成为一个字典,其中键是列名,值是单元格中的数据

>>> df.to_dict('records')
>
[{'a': 'red', 'b': 0.5}, 
 {'a': 'yellow', 'b': 0.25}, 

index - 类似于'records',但是一个字典字典,其中键作为索引标签(而不是列表)

>>> df.to_dict('index')

{0: {'a': 'red', 'b': 0.5},
 1: {'a': 'yellow', 'b': 0.25},
 2: {'a': 'blue', 'b': 0.125}}

到此这篇关于Pandas DataFrame转换为字典的方法的文章就介绍到这了,更多相关Pandas DataFrame转换为字典内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!

标签:pandas  numpy  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!