从dataframe列创建一个字典,该字典的单元格中有多个值

最后发布: 2019-10-03 08:58:01


问题

我有一个这样的数据框,

在此处输入图片说明

我想以此创建一个字典,以在另一个数据帧中重新映射一列(如果您查看第330行,它具有524和545。我想在另一个数据帧中分配一个值(330))

因此,我使用此代码创建了字典。

di = new2.T.to_dict('list')

但是我得到的字典是这样的,

 {0: ['-1'], 1: ['187'], 2: ['212'], 3: ['30'], 4: ['209'], 5: ['213'], 6: ['214'], 7: ['238'], 8: ['544'], 9: ['557'], 10: ['317'], 11: ['516'], 12: ['571'], 13: ['184, 549'], 14: ['64'], 15: ['43'], 16: ['584'], 17: ['185'], 18: ['190'], 19: ['218'], 20: ['174'], 21: ['550'], 22: ['138'], 23: ['1'], 24: ['311'], 25: ['576'], 26: ['500'], 27: ['208, 241'], 28: ['16'], 29: ['327'], 30: ['3, 34, 50'], 31: ['332'], 32: ['520'], 33: ['491'], 34: ['535'], 35: ['523'], 36: ['119'], 37: ['482'], 38: ['574'], 39: ['165'], 40: ['370'], 41: ['51, 62, 73, 87, 101, 120, 199, 240, 304, 360, 506'], 

当我使用这段代码将其反转时

{value: key for key, values in di.items() for value in values}

变成这个,

 {'-1': 0, '187': 1, '212': 2, '30': 3, '209': 4, '213': 5, '214': 6, '238': 7, '544': 8, '557': 9, '317': 10, '516': 11, '571': 12, '184, 549': 13, '64': 14, '43': 15, '584': 16, '185': 17, '190': 18, '218': 19, '174': 20, '550': 21, '138': 22, '1': 23, '311': 24, '576': 25, '500': 26, '208, 241': 27, '16': 28, '327': 29, '3, 34, 50': 30, '332': 31, '520': 32, '491': 33, '535': 34, '523': 35, '119': 36, '482': 37, '574': 38, '165': 39, '370': 40, '51, 62, 73, 87, 101, 120, 199, 240, 304, 360, 506': 41, '525': 42, 

但我想将它们分别映射,例如,

184: 13,
549: 13,

而不是这个

'184, 549': 13,

并使用.map()函数使用字典对其进行映射

python python-3.x dictionary
回答

问题是您在列表中有字符串,只需拆分字符串即可:

di = {
    27: ['208, 241'],
    28: ['16'],
    29: ['327'],
    30: ['3, 34, 50'],
    31: ['332'],
    32: ['520'],
    33: ['491']
}

result = {value: key for key, values in di.items() for value in values[0].split(', ')}
print(result)

输出量

{'208': 27, '241': 27, '16': 28, '327': 29, '3': 30, '34': 30, '50': 30, '332': 31, '520': 32, '491': 33}

注意,我以di一小部分为例,这可以应用于整个字典。