pandas关于to 您所在的位置:网站首页 series转换为字典 pandas关于to

pandas关于to

2024-01-11 15:00| 来源: 网络整理| 查看: 265

to_dict()使用

Pandas 处理数据的基本类型为DataFrame,数据清洗时不可必然会关系到数据类型转化问题,Pandas在这方面也做的也非常不错,其中经常用的是 DataFrame.to_dict()函数之间转化为字典类型;除了转化为字典之外,Pandas还提供向 json、html、latex、csv等格式的转换 to_dict()函数基本语法:

DataFrame.to_dict(self,orient = 'dict',into = )

注意:函数中只需填一个参数:orient即可,但对于写入的orient不同,字典的构造方式也不同,其中有一种是列表形式

orient = 'dict' 函数默认,转换后的字典形式:{column:{index:value}}

orient = 'list'转换后字典形式:{column:[values]}

orient = 'series'转换后字典形式:{column:Series(value)}

orient = 'split'转换后字典形式:{'index':[index],'columns':[columns],'data':[values]}

orient = 'records'转换后list形式:[{column:value}...{column:value}]

orient = 'index'转换后字典形式:{index:{column:value}}

举例说明 import pandas as pd df =pd.DataFrame({'name':['devil','angel'],'age':[12,18]},index =['10086','10089'])

在这里插入图片描述

orient = ‘dict’ 能够方便得到:在某一列对应的行名与各值之间的字典数据类型 {column -> {index -> value}}构造好的字典形式:{第一列的列名:{第一行的行名:value值,第二行行名,value值},…}栗子:在源数据上想要得到name这一列行名与各值之间的字典,直接在生成的字典中查询列名为name查询方式:df[key1][key2] df.to_dict(orient = 'dict') df.to_dict(orient = 'dict')['name']

在这里插入图片描述

orient = ‘list’ 能够方便得到:某一列各值所生成的列表集合{column -> [values]}生成字典中key为各列名,value为各列对应值的列表栗子:在源数据上想要得到name对应值的列表查询方式:df[keys][index] df.to_dict(orient = 'list') df.to_dict(orient = 'list')['name']

在这里插入图片描述

orient = ‘series’ orient = 'series’和orient = 'list’的唯一区别:这里的value是series数据类型,而list是列表类型{column -> Series(values)}查询方式:df[key1][key2]或df[key1] df.to_dict(orient = 'series') df.to_dict(orient = 'series')['name']

在这里插入图片描述

orient = ‘split’ 可以方便得到:DataFrame数据表中全部列名或者行名的列表形式{index -> [index], columns -> [columns], data -> [values]}得到三个键值对,列名、行名、值各一个,value统一都是列表形式栗子:想要得到全部的列名调用方式:df[‘index’],df[‘columns’],df[‘data’] df.to_dict(orient = 'split') df.to_dict(orient = 'split')['columns']

在这里插入图片描述

orient = ‘records’ 可以方便得到:列名与某一行值形成的字典数据返回的数据类型不是dict; 而是list列表形式,由全部列名与每一行的值形成一一对应的映射关系[{column -> value}, … , {column -> value}]栗子:想要第1行{column:value}得数据调用方式:df[index][key1] df.to_dict(orient = 'records') df.to_dict(orient = 'records')[0]

在这里插入图片描述

orient = ‘index’ orient = 'index’与orient = 'dict’刚好相反,某一行中列名与值之间一一对应关系{index -> {column -> value}} df.to_dict(orient = 'index') df.to_dict(orient = 'index')['10086']

在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有