python pandas将DataFrame转换为dict

之前在知乎上看到有网友提问,如何将DataFrame转换为dict,专门研究了一下,pandas在0.21.0版本中是提供了这个方法的,下面,学习一下:
通过调用help方法,该方法只需传入一个参数,并根据参数的内容返回不同的结果,下面是pandas的官方文档说明:
Parameters
----------
orient : str {‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’}
Determines the type of the values of the dictionary.

    - 'dict' (default) : dict like {column -> {index -> value}}
    - 'list' : dict like {column -> [values]}
    - 'series' : dict like {column -> Series(values)}
    - 'split' : dict like
      {'index' -> [index], 'columns' -> [columns], 'data' -> [values]}
    - 'records' : list like
      [{column -> value}, ... , {column -> value}]
    - 'index' : dict like {index -> {column -> value}}

    Abbreviations are allowed. `s` indicates `series` and `sp`
    indicates `split`.

举例如下:

>>> import pandas as pd
>>> df = pd.read_excel(r'D:/myExcel/1.xlsx')
>>> df
  name   C
0   lc  45
1   lc  23
2   lb  88
3   lc  23

# 默认是'dict'dict like {column -> {index -> value}}
>>> df.to_dict()
{'name': {0: 'lc', 1: 'lc', 2: 'lb', 3: 'lc'}, 
'C': {0: 45, 1: 23, 2: 88, 3: 23}}

# list dict like {column -> [values]}
>>> df.to_dict('list')
{'name': ['lc', 'lc', 'lb', 'lc'], 'C': [45, 23, 88, 23]}
>>> df.to_dict('series')
{'name': 0    lc
1    lc
2    lb
3    lc

#  'series' : dict like {column -> Series(values)}
Name: name, dtype: object, 'C': 0    45
1    23
2    88
3    23
Name: C, dtype: int64}

# 'split' : dict like
  {'index' -> [index], 
  'columns' -> [columns], 'data' -> [values]}
>>> df.to_dict('split')
{'index': [0, 1, 2, 3], 'columns': ['name', 'C'], 
'data': [['lc', 45], ['lc', 23], ['lb', 88], ['lc', 23]]}

# 'index' : dict like {index -> {column -> value}}
>>> df.to_dict('index')
{0: {'name': 'lc', 'C': 45}, 1: {'name': 'lc', 'C': 23}, 
2: {'name': 'lb', 'C': 88}, 3: {'name': 'lc', 'C': 23}}

# 'records' : list like
  [{column -> value}, ... , {column -> value}]
>>> df.to_dict('records')
[{'name': 'lc', 'C': 45}, {'name': 'lc', 'C': 23},
 {'name': 'lb', 'C': 88}, {'name': 'lc', 'C': 23}]
>>> 

哈哈,以上就是python小工具关于to_dict()的介绍。有兴趣的话,欢迎关注公众号:python小工具。
python pandas将DataFrame转换为dict_第1张图片

你可能感兴趣的:(python pandas将DataFrame转换为dict)