【问题标题】:create one dict from list of dicts in DataFrame从 DataFrame 中的字典列表创建一个字典
【发布时间】:2020-08-31 01:07:03
【问题描述】:

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

但它让我无法解决问题。

谢谢!

【问题讨论】:

    标签: python pandas dictionary lambda


    【解决方案1】:

    让我们试试ChainMap

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

    【讨论】:

    • 看起来它正在工作!但它是什么黑魔法以及为什么我从未听说过 ChainMap :)
    • @YORBEN_S 谢谢,这似乎是最简单的方法。可惜没听说过ChainMap。我的错!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-06-20
      • 2017-06-26
      • 2017-05-05
      • 2018-11-06
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2021-12-07
      • 2021-03-17
      相关资源
      最近更新 更多