2016-06-10 120 views
0

我有以下直接從SQL查詢數據幀:如何創建一個數據幀字典詞典使用Python的大熊貓

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)) 

有人可以建議更好的解決方案NS?

回答

3

你可以使用:

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

感謝的人。真的很棒的解決方案! – ibarant

+0

不客氣! – Stefan

相關問題