通过将列值映射到标头来在pandas中创建字典

时间:2017-10-04 03:31:47

标签: python pandas dictionary

我有以下数据框:

F1:


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

我需要通过将列中的所有值映射到列的标题来创建字典,如下所示:

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 }

我创建了每个列的列表并将其映射到标题,但我不知道如何创建这样的字典。谢谢!

3 个答案:

答案 0 :(得分: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'}

如果您收到此错误:

AttributeError: 'DataFrame' object has no attribute 'melt

这意味着您使用的是旧版本的pandas(< 0.20),因此请使用pd.melt

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

答案 1 :(得分:3)

添加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'}]

答案 2 :(得分:3)

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

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