如何使用python'从数据帧创建字典字典;熊猫

如何使用python'从数据帧创建字典字典;熊猫,python,pandas,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

我直接从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))
有人能提出更好的解决方案吗?

您可以使用:

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'}}
您可以使用:

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'}}