1

I have the following data frame:

F1:


head       drowsiness     sweat       
head_P     D_P            sw_f
head_S     D-H            sw_h
head_F     D_L            sw_l

I need to create a dictionary by mapping all the values in columns to the header of the columns as follows:

Dic = {head_p:head, head_S: head, head_F: head,  D_P: drowsiness, D-H:drowsiness ,  D_L: drowsiness,   sw_f: sweat,  sw_h: sweat , sw_l: sweat }

I created a list of each column and mapped it to the header, but I do not know how to create such a dictionary. Thank you!

cs95
  • 379,657
  • 97
  • 704
  • 746
Mary
  • 1,142
  • 1
  • 16
  • 37

3 Answers3

3

melt + set_index + to_dict:

df

     head drowsiness sweat
0  head_P        D_P  sw_f
1  head_S        D-H  sw_h
2  head_F        D_L  sw_l

df.melt().set_index('value').to_dict()['variable']

{'D-H': 'drowsiness',
 'D_L': 'drowsiness',
 'D_P': 'drowsiness',
 'head_F': 'head',
 'head_P': 'head',
 'head_S': 'head',
 'sw_f': 'sweat',
 'sw_h': 'sweat',
 'sw_l': 'sweat'}

If you get this error:

AttributeError: 'DataFrame' object has no attribute 'melt

That means you're using an older version of pandas (<0.20), so instead, use pd.melt:

pd.melt(df).set_index('value').to_dict()['variable']
cs95
  • 379,657
  • 97
  • 704
  • 746
  • it returns the following error: AttributeError: 'DataFrame' object has no attribute 'melt' – Mary Oct 04 '17 at 03:47
  • @Mary You must be using an old version of pandas. Change to `pd.melt(df).set_index('value').to_dict()['variable']` – cs95 Oct 04 '17 at 03:52
3

Add T

df.melt().set_index('value').T.to_dict('records')
Out[277]: 
[{'D-H': 'drowsiness',
  'D_L': 'drowsiness',
  'D_P': 'drowsiness',
  'head_F': 'head',
  'head_P': 'head',
  'head_S': 'head',
  'sw_f': 'sweat',
  'sw_h': 'sweat',
  'sw_l': 'sweat'}]
BENY
  • 317,841
  • 20
  • 164
  • 234
3

Option 1

dict(zip(df.values.ravel(), df.columns.repeat(len(df))))

{'D-H': 'drowsiness',
 'D_L': 'sweat',
 'D_P': 'head',
 'head_F': 'sweat',
 'head_P': 'head',
 'head_S': 'drowsiness',
 'sw_f': 'head',
 'sw_h': 'drowsiness',
 'sw_l': 'sweat'}

Option 2

dict((v, h) for r, h in zip(df.values, df.columns) for v in r)

{'D-H': 'drowsiness',
 'D_L': 'sweat',
 'D_P': 'head',
 'head_F': 'sweat',
 'head_P': 'head',
 'head_S': 'drowsiness',
 'sw_f': 'head',
 'sw_h': 'drowsiness',
 'sw_l': 'sweat'}
piRSquared
  • 285,575
  • 57
  • 475
  • 624