Python中将dataframe转换为字典的实例
有时候,在Python中需要将dataframe类型转换为字典类型,下面的方法帮助我们解决这一问题。任务代码。
#encoding:utf-8
importpandasaspd
a=['Name','Age','Gender']
b=['Ali','19','China']
data=pd.DataFrame(zip(a,b),columns=['project','attribute'])
printdata
dict_country=data.set_index('project').T.to_dict('list')
printdict_country
输出显示
projectattribute
0NameAli
1Age19
2GenderChina
{'Gender':['China'],'Age':['19'],'Name':['Ali']}
值得注意的是,转置之前需要设置指定的索引,否则会按照默认索引转换成这样:
{0:['Name','Ali'],1:['Age','19'],2:['Gender','China']}
以上这篇Python中将dataframe转换为字典的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。