从数据框创建字典

时间:2020-06-01 14:33:34

标签: python pandas dictionary

我正在尝试将数据帧转换为以下格式的字典:

df
    name   age country state  pincode
0  user1  10.0      in    tn      1.0
1  user2  11.0      us    tx      2.0
2  user3  12.0      eu    fr      3.0
{
   'user1':{'age':10,'country':'in','state':'tn','pincode':1},
   'user2':{'age':11,'country':'us','state':'tx','pincode':2},
   'user3':{'age':12,'country':'eu','state':'fr','pincode':3}
}

我目前正在通过以下声明来这样做:

op = {}
for i, row in df.iterrows():
    op[row['name']] = {'age':row['age'],'country':row['country'],'state':row['state'],'pincode':row['pincode']}

如果要在df中添加其他列,我希望该解决方案能够正常工作。例如电话号码。由于我编写的语句是静态的,因此不会在输出中给我其他行。 大熊猫中有内置的方法吗?

3 个答案:

答案 0 :(得分:1)

您要先将name设置为索引:

df.set_index('name').to_dict('index')

输出:

{'user1': {'age': 10.0, 'country': 'in', 'state': 'tn', 'pincode': 1.0},
 'user2': {'age': 11.0, 'country': 'us', 'state': 'tx', 'pincode': 2.0},
 'user3': {'age': 12.0, 'country': 'eu', 'state': 'fr', 'pincode': 3.0}}

答案 1 :(得分:1)

DataFrame.set_indexorient='index'DataFrame.to_dict一起使用:

d = df.set_index('name').to_dict(orient='index')
print (d)
{'user1': {'age': 10.0, 'country': 'in', 'state': 'tn', 'pincode': 1.0}, 
 'user2': {'age': 11.0, 'country': 'us', 'state': 'tx', 'pincode': 2.0}, 
 'user3': {'age': 12.0, 'country': 'eu', 'state': 'fr', 'pincode': 3.0}}

如果可能的话,可以省略其他列,或者在选择以下内容之前对其进行裁剪:

d = df.set_index('name')[['age','country','state','pincode']].to_dict(orient='index')

答案 2 :(得分:1)

这可能不是很可读,但是这里有一个单行字典理解:

{k:{a:b for a,b in zip(df.columns.tolist()[1:], v)}
 for k,v in zip(df['name'].to_list(), df.iloc[:,1:].to_numpy().tolist())}