给定以下字典:
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']}
实际上,我使用的是键位置和在字典中查找值的位置,如果oldvalue匹配字典中的值,然后将其替换为newval我一直在看更新函数,我把我的表转换成字典,但我不确定如何应用到我的例子。
首先制作一个嵌套的系列/字典来映射键/位置/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
可以使用:
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']}