从DataFrame中的字典列表中创建一个字典

时间:2020-05-14 13:17:39

标签: python pandas dictionary lambda

我在用简单的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']})

但是它使我无处可寻。

谢谢!

2 个答案:

答案 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':...  
相关问题