gpt4 book ai didi

python - 从数据框列创建一个字典,该字典的单元格中有多个值

转载 作者:行者123 更新时间:2023-12-01 00:30:34 25 4
gpt4 key购买 nike

我有一个像这样的数据框,

enter image description here

我想从中创建一个字典来重新映射另一个数据框中的列(如果您查看第 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()函数使用字典来映射它

最佳答案

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

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 的一小部分作为示例,这可以应用于整个词典。

关于python - 从数据框列创建一个字典,该字典的单元格中有多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58215635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com