简体   繁体   English

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

[英]create one dict from list of dicts in DataFrame

I'm struggling with simple lambda to convert list of nested dicts stored in df column but got stuck.我正在努力使用简单的 lambda 来转换存储在 df 列中的嵌套字典列表,但被卡住了。

My df looks like我的 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}}]

What I'd like to achieve is to have it like that:我想要实现的是这样:

index   synthkey    celldata
0   870322681ffffff {'3400_251': {'s': -77, 'q': -8},'3400_426': {'s': -116, 'q': -16}}

I've tried multiple attempts like:我尝试了多次尝试,例如:

df['dicts'] = df['celldata'].apply(lambda x: {}.update(*x)) 

or或者

df['dicts'] = df.apply(lambda x: {*x['celldata']})

but it got me nowhere near the solution.但这让我离解决方案还差得很远。

Thanks!谢谢!

Let us try ChainMap让我们试试ChainMap

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

Using a simple for-loop to merge the dictionaries using merge_dict = {**dict_one, **dict_two} .使用简单的 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':...  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM