Python中将dataframe转换为字典的实例

yipeiwu_com6年前Python基础

有时候,在Python中需要将dataframe类型转换为字典类型,下面的方法帮助我们解决这一问题。 任务代码。

# encoding: utf-8

import pandas as pd
a = ['Name', 'Age', 'Gender']
b = ['Ali', '19', 'China']
data = pd.DataFrame(zip(a, b), columns=['project', 'attribute'])
print data
dict_country = data.set_index('project').T.to_dict('list')
print dict_country

输出显示

 project attribute
0  Name    Ali
1   Age    19
2 Gender   China
{'Gender': ['China'], 'Age': ['19'], 'Name': ['Ali']}

值得注意的是,转置之前需要设置指定的索引,否则会按照默认索引转换成这样:

{0: ['Name', 'Ali'], 1: ['Age', '19'], 2: ['Gender', 'China']}

以上这篇Python中将dataframe转换为字典的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python基于queue和threading实现多线程下载实例

本文实例讲述了python基于queue和threading实现多线程下载的方法,分享给大家供大家参考。具体方法如下: 主代码如下: #download worker qu...

Python的mysql数据库的更新如何实现

Python的mysql数据库的更新           Python的mysql数据库的更新操...

python定时任务 sched模块用法实例

这篇文章主要介绍了python定时任务 sched模块用法实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 通过sched模块可以实...

Python django使用多进程连接mysql错误的解决方法

Python django使用多进程连接mysql错误的解决方法

问题 mysql 查询出现错误 error: (2014, "Commands out of sync; you can't run this command now")1 查询 m...

python 调用钉钉机器人的方法

以text格式的消息为例:(只需修改content后的内容) Import json Import requests url='https://oapi.dingtalk.com...