首页 > 编程 > Python > 正文

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

2019-11-25 14:56:25
字体:
来源:转载
供稿:网友

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

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

输出显示

 project attribute0  Name    Ali1   Age    192 Gender   China{'Gender': ['China'], 'Age': ['19'], 'Name': ['Ali']}

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

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

以上这篇Python中将dataframe转换为字典的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表