gpt4 book ai didi

python - 从嵌套字典中的值构造数据框

转载 作者:太空狗 更新时间:2023-10-30 02:52:32 25 4
gpt4 key购买 nike

我有一个字典列表列表,我正在尝试将其转换为 pandas DataFrame 但我无法使用 pandas.DataFrame.from_dict() 因为我想要的值“名称”键作为列标题,“持续时间”键的值作为行值。关于如何使这项工作有任何建议吗?

[[{'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

最佳答案

您可以通过 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

关于python - 从嵌套字典中的值构造数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52993987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com