pandas 使用update以数据表/字典中的新信息更新巢状字典

gmol1639  于 2022-11-20  发布在  其他
关注(0)|答案(2)|浏览(296)

给定以下字典:

dict1 = {'AA':['THISISSCARY'],
         'BB':['AREYOUAFRAID'],
         'CC':['DONOTWORRY']}

我想根据下表中的信息更新字典中的值

Table = pd.DataFrame({'KEY':['AA','AA','BB','CC'],
                      'POSITION':[2,4,9,3],
                      'oldval':['I','I','A','O'],
                      'newval':['X','X','U','I']})

看起来像这样

KEY   POSITION  oldval  newval
0   AA         2      I      X
1   AA         4      I      X
2   BB         9      A      U
3   CC         3      O      I

最终结果应如下所示:

dict1 = {'AA':['THXSXSSCARY'],
         'BB':['AREYOUAFRUID'],
         'CC':['DONITWORRY']}

实际上,我使用KEYPOSITION来查找值在字典中的位置,如果oldvalue与字典中的值匹配,则将其替换为newval
我一直在研究update函数,在这里我将把我的表转换成字典,但是我不确定如何应用到我的例子中。

mrwjdhj3

mrwjdhj31#

首先创建一个嵌套的Series/字典来Mapkey/position/newval,然后使用字典解析:

s = (Table.groupby('KEY')
     .apply(lambda d: d.set_index('POSITION')['newval'].to_dict())
     )

out = {k: [''.join(s.get(k, {}).get(i, x) for i,x in enumerate(v[0]))]
       for k,v in dict1.items()
       }

输出量:

{'AA': ['THXSXSSCARY'],
 'BB': ['AREYOUAFRUID'],
 'CC': ['DONITWORRY']}

中间体s

KEY
AA    {2: 'X', 4: 'X'}
BB            {9: 'U'}
CC            {3: 'I'}
dtype: object
bakd9h0s

bakd9h0s2#

您可以用途:

dict_df=Table.to_dict('records')
print(dict_df)
'''
[{'KEY': 'AA', 'POSITION': 2, 'oldval': 'I', 'newval': 'X'}, {'KEY': 'AA', 'POSITION': 4, 'oldval': 'I', 'newval': 'X'}, {'KEY': 'BB', 'POSITION': 9, 'oldval': 'A', 'newval': 'U'}, {'KEY': 'CC', 'POSITION': 3, 'oldval': 'O', 'newval': 'I'}]
'''

for i in list(dict1.keys()):
    for j in dict_df:
        if i == j['KEY']:
            mask=list(dict1[i][0])
            mask[j['POSITION']]=j['newval']
            dict1[i]=["".join(mask)]
print(dict1)
# {'AA': ['THXSXSSCARY'], 'BB': ['AREYOUAFRUID'], 'CC': ['DONITWORRY']}

相关问题