当前位置:主页 > 软件编程 > Python代码 >

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

时间:2021-07-17 08:08:37 | 栏目: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']}

您可能感兴趣的文章:

相关文章