首页 > 编程 > Python > 正文

对pandas中to_dict的用法详解

2020-02-15 21:38:39
字体:
来源:转载
供稿:网友

简介: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 sex1086 3rd 31.194181 UNKNOWN   UNKNOWN male12 1st 31.194181 Cherbourg   Paris, France female1036 3rd 31.194181 UNKNOWN   UNKNOWN male833 3rd 32.000000 Southampton Foresvik, Norway Portland, ND male1108 3rd 31.194181 UNKNOWN   UNKNOWN male562 2nd 41.000000 Cherbourg   New York, NY male437 2nd 48.000000 Southampton Somerset / Bernardsville, NJ female663 3rd 26.000000 Southampton   UNKNOWN male669 3rd 19.000000 Southampton   England male507 2nd 31.194181 Southampton  Petworth, Sussex maleIn[10]: data_dict=data.to_dict(orient= 'dict')In[11]: data_dictOut[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: 'Cherbourg', 663: 'Southampton', 669: 'Southampton', 833: 'Southampton', 1036: 'UNKNOWN', 1086: 'UNKNOWN', 1108: 'UNKNOWN'}, 'home.dest': {12: 'Paris, France', 437: 'Somerset / Bernardsville, NJ', 507: 'Petworth, Sussex', 562: 'New York, NY', 663: 'UNKNOWN', 669: 'England', 833: 'Foresvik, Norway Portland, ND', 1036: 'UNKNOWN', 1086: 'UNKNOWN', 1108: 'UNKNOWN'}, 'pclass': {12: '1st', 437: '2nd', 507: '2nd', 562: '2nd', 663: '3rd', 669: '3rd', 833: '3rd', 1036: '3rd', 1086: '3rd', 1108: '3rd'}, 'sex': {12: 'female', 437: 'female', 507: 'male', 562: 'male', 663: 'male', 669: 'male', 833: 'male', 1036: 'male', 1086: 'male', 1108: 'male'}}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表