从DataFrame中的dict列表创建一个dict

2024-10-03 19:21:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力用简单的lambda转换存储在df列中的嵌套dict列表,但被卡住了

我的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']})

但这并没有让我接近解决方案

谢谢


Tags: lambdadf列表indexupdate解决方案dictapply
2条回答

让我们试试ChainMap

from collections import ChainMap
df['dicts']=df['celldata'].map(lambda x : dict(ChainMap(*x)))

使用简单的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':...  

相关问题 更多 >