【问题标题】:Pandas build dataframe from a list of single dicts [duplicate]Pandas 从单个字典列表中构建数据框 [重复]
【发布时间】:2021-01-17 18:39:49
【问题描述】:

我有一个单独的字典列表:

foo = [
{'A': 'a1'}, {'B': 'b1'},{'C': 'c1'},
 {'A': 'a2'}, {'B': 'b2'}, {'C': 'c2'},
 {'A': 'a3'}, {'B': 'b3'},{'C': 'c3'}
]

我想构建一个这样的DataFrame。

我尝试了这个解决方案来将这个字典列表分组到一个字典中 Combine values of same keys in a list of dicts

bar = {
    k: [d.get(k) for d in foo]
    for k in set().union(*foo)
}

pd.DataFrame(bar)

但是输出看起来不太好。

有人可以帮忙吗?

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    首先转换为列的字典:

    from collections import defaultdict                                                                
    
    bar = defaultdict(list)                                                                            
    
    for dict_ in foo: 
        for key, value in dict_.items(): 
            bar[key].append(value) 
    

    然后就变得微不足道了:

    pd.DataFrame(bar)                                                                                  
    # Out 
    #     A   B   C
    # 0  a1  b1  c1
    # 1  a2  b2  c2
    # 2  a3  b3  c3
    

    【讨论】:

      【解决方案2】:

      您可以更改字典理解以过滤缺失值:

      bar = {
          k: [d[k] for d in foo if k in d]
          for k in set().union(*foo)
      }
      

      编辑:@Marat 发布的解决方案也可以。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 2016-05-12
        • 2015-06-29
        • 2017-04-27
        • 1970-01-01
        • 1970-01-01
        • 2017-07-03
        相关资源
        最近更新 更多