Python中将dataframe转换为字典的实例
有时候,在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']}
相关推荐
FlySky 2020-11-02
逍遥友 2020-10-26
taiyangshenniao 2020-10-05
flycony 2020-09-23
jacktangj 2020-09-18
YENCSDN 2020-09-15
lsjweiyi 2020-09-14
digwtx 2020-09-14
拾毅者 2020-09-14
zlxcsdn 2020-09-13
weiiron 2020-08-17
amazingbo 2020-08-16
郗瑞强 2020-08-16
lispython 2020-08-16
fengling 2020-08-15
xiesheng 2020-08-02
葫芦小金刚 2020-07-28
StevenSun空间 2020-07-26