我在用简单的lambda进行转换以转换存储在df列中但被卡住的嵌套字典列表。
我的df看起来
index synthkey celldata
0 870322681ffffff [{'3400_251': {'s': -77, 'q': -8}}, {'3400_426': {'s': -116, 'q': -16}}]
0 87032268effffff [{'3400_376': {'s': -97, 'q': -12}}, {'3400_426': {'s': -88, 'q': -12}}]
我想要实现的就是这样:
index synthkey celldata
0 870322681ffffff {'3400_251': {'s': -77, 'q': -8},'3400_426': {'s': -116, 'q': -16}}
我尝试了多次尝试,例如:
df['dicts'] = df['celldata'].apply(lambda x: {}.update(*x))
或
df['dicts'] = df.apply(lambda x: {*x['celldata']})
但是它使我无处可寻。
谢谢!
答案 0 :(得分:4)
让我们尝试ChainMap
from collections import ChainMap
df['dicts']=df['celldata'].map(lambda x : dict(ChainMap(*x)))
答案 1 :(得分:0)
使用简单的for循环使用merge_dict = {**dict_one, **dict_two}
合并字典。
df = pd.DataFrame([{
'index': 0,
'synthkey': '870322681ffffff',
'celldata': [{'3400_251': {'s': -77, 'q': -8}}, {'3400_426': {'s': -116, 'q': -16}}]
},{
'index': 0,
'synthkey': '87032268effffff',
'celldata': [{'3400_376': {'s': -97, 'q': -12}}, {'3400_426': {'s': -88, 'q': -12}}]
}])
def merge_dicts(list_of_dicts):
out = {}
for elem in list_of_dicts:
out = {**out, **elem}
return out
df['new'] = df['celldata'].apply(merge_dicts)
print(df.head())
# index synthkey celldata \
# 0 0 870322681ffffff [{'3400_251': {'s': -77, 'q': -8}}, {'3400_426...
# 1 0 87032268effffff [{'3400_376': {'s': -97, 'q': -12}}, {'3400_42...
# new
# 0 {'3400_251': {'s': -77, 'q': -8}, '3400_426': ...
# 1 {'3400_376': {'s': -97, 'q': -12}, '3400_426':...