dict存到pandas_对pandas中to_dict的用法详解

简介: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值