简介:pandas 中的to_dict 可以对DataFrame类型的数据进行转换
可以选择六种的转换类型,分别对应于参数 ‘dict', ‘list', ‘series', ‘split', ‘records', ‘index',下面逐一介绍每种的用法
Help on method to_dict in module pandas.core.frame:
to_dict(orient='dict') method of pandas.core.frame.DataFrame instance
Convert DataFrame to dictionary.
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}}
.. versionadded:: 0.17.0
Abbreviations are allowed. `s` indicates `series` and `sp`
indicates `split`.
Returns
-------
result : dict like {column -> {index -> value}}
1、选择参数orient='dict'
dict也是默认的参数,下面的data数据类型为DataFrame结构, 会形成 {column -> {index -> value}}这样的结构的字典,可以看成是一种双重字典结构
- 单独提取每列的值及其索引,然后组合成一个字典
- 再将上述的列属性作为关键字(key),值(values)为上述的字典
查询方式为 :data_dict[key1][key2]
- data_dict 为参数选择orient='dict'时的数据名
- key1 为列属性的键值(外层)
- key2 为内层字典对应的键值
data
Out[9]:
pclass age embarked home.dest sex
1086 3rd 31.194181 UNKNOWN UNKNOWN male
12 1st 31.194181 Cherbourg Paris, France female
1036 3rd 31.194181 UNKNOWN UNKNOWN male
833 3rd 32.000000 Southampton Foresvik, Norway Portland, ND male
1108 3rd 31.194181 UNKNOWN UNKNOWN male
562 2nd 41.000000 Cherbourg New York, NY male
437 2nd 48.000000 Southampton Somerset / Bernardsville, NJ female
663 3rd 26.000000 Southampton UNKNOWN male
669 3rd 19.000000 Southampton England male
507 2nd 31.194181 Southampton Petworth, Sussex male
In[10]: data_dict=data.to_dict(orient= 'dict')
In[11]: data_dict
Out[11]:
{'age': {12: 31.19418104265403,
437: 48.0,
507: 31.19418104265403,
562: 41.0,
663: 26.0,
669: 19.0,
833: 32.0,
1036: 31.19418104265403,
1086: 31.19418104265403,
1108: 31.19418104265403},
'embarked': {12: 'Cherbourg',
437: 'Southampton',
507: 'Southampton',
562: 'Ch