【问题标题】:Construct dataframe from values in nested dictionary从嵌套字典中的值构造数据框
【发布时间】:2019-03-30 08:15:42
【问题描述】:

我有一个字典列表,我试图将其转换为 pandas DataFrame,但我无法使用 pandas.DataFrame.from_dict(),因为我希望 'name' 键的值是列标题和'duration' 键的值是行值。关于如何完成这项工作的任何建议?

[[{'duration': 21.82, 'name': 'ABC'},
{'duration': 3.9, 'name': 'DEF'},
{'duration': 105.78, 'name': 'GHI'},
{'duration': 63.14, 'name': 'JKL'}],
[{'duration': 18.9, 'name': 'ABC'},
{'duration': 56.01, 'name': 'DEF'},
{'duration': 38.36, 'name': 'GHI'},
{'duration': 34.16, 'name': 'JKL'}]]

期望的输出:

    ABC    DEF    GHI     JKL
0  21.82   3.9   105.78   63.14
1  18.9   56.01  38.36    34.16

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    您可以通过itertools.chain 展平您的列表列表,然后通过pivot 您的数据框。这里的技巧是使用一个按您的石斑鱼累积计数的索引。

    from itertools import chain
    
    df = pd.DataFrame(list(chain.from_iterable(L)))
    
    res = df.pivot(index=df.groupby('name').cumcount(), columns='name')
    res.columns = res.columns.droplevel(0)  # remove unwanted column level
    
    print(res)
    
    name    ABC    DEF     GHI    JKL
    0     21.82   3.90  105.78  63.14
    1     18.90  56.01   38.36  34.16
    

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 2012-11-14
      • 2021-01-04
      • 2021-11-16
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多