2016-06-10 2 views
0

I SQL 쿼리에서 직접 다음 dataframe이 : 나는 시도파이썬의 팬더를 사용하여 dataframe에서 사전의 사전을 만드는 방법

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

:

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 

내가 같은 사전을 얻을 필요를 다음 코드는 있지만 모든 값과 라벨을 나열합니다.

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

누군가가 더 나은 solutio를 제안 할 수 있습니까? 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

관련 문제