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!

2
  • You should understand that dictionaries cannot contain duplicate keys, so this is not possible. What else do you have in mind? Commented Oct 4, 2017 at 3:33
  • @COLDSPEED, I am sorry, I edited it. Commented Oct 4, 2017 at 3:39

3 Answers 3

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']
Sign up to request clarification or add additional context in comments.

2 Comments

it returns the following error: AttributeError: 'DataFrame' object has no attribute 'melt'
@Mary You must be using an old version of pandas. Change to pd.melt(df).set_index('value').to_dict()['variable']
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'}]

Comments

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

1 Comment

dude nice one :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.