如何使用python的pandas从数据框架创建字典词典

时间:2016-06-10 16:39:36

标签: python pandas

我直接从SQL查询中获得以下数据框:

Question            tagID   Answer  
Primary purpose     62      Other  
Primary purpose     226     Learn how to use  
Primary purpose     227     Technical Support  
Primary purpose     292     Purchase  
Language            246     English  
Language            247     French   
Language            248     German  
Device              102     Desktop  
Device              103     Tablet  
Device              104     Mobile  

我需要得到一个字典:

{Primary purpose: {62: 'Other', 226:'Learn how to use',227:'Technical Support',292:'Purchase' }, Language:{246:'English', 247:'French',248:'German'}, Device: {102: 'Desktop', 103:'Mobile', 104:'Tablet'}} 

我尝试了以下代码,但它列出了所有值和标签:

    SS_valueLabelsSQL = {}
    for q in df['Question']:
       SS_valueLabelsSQL[q] = {}
       labels = df['Answer'].tolist()
       values = df['tagID'].tolist()
       SS_valueLabelsSQL[q] = dict(zip(values,labels))

有人可以提出更好的解决方案吗?

1 个答案:

答案 0 :(得分:4)

您可以使用:

df.set_index('Question').groupby(level='Question').apply(lambda x: x.set_index('tagID').squeeze().to_dict()).to_dict()

得到:

{'Language': {248: 'German', 246: 'English', 247: 'French'}, 'Primary purpose': {226: 'Learn how to use', 227: 'Technical Support', 292: 'Purchase', 62: 'Other'}, 'Device': {104: 'Mobile', 102: 'Desktop', 103: 'Tablet'}}