gpt4 book ai didi

python - 字典列表中的 Pandas DataFrame

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:47 24 4
gpt4 key购买 nike

我有一个数据结构,它是一个字典列表的列表:

[
[{'Height': 86, 'Left': 1385, 'Top': 215, 'Width': 86},
{'Height': 87, 'Left': 865, 'Top': 266, 'Width': 87},
{'Height': 103, 'Left': 271, 'Top': 506, 'Width': 103}],
...
]

我可以将它转换为数据框:

detections[0:1]
df = pd.DataFrame(detections)
pd.DataFrame(df.apply(pd.Series).stack())

产生:

stacked data frame

这几乎就是我想要的,但是:

我如何将每个单元格中的字典变成包含“左”、“上”、“宽度”、“高度”列的行?

最佳答案

添加到 Psidom's answer ,也可以使用 itertools.chain.from_iterable 来展平列表。

from itertools import chain

pd.DataFrame(list(chain.from_iterable(detections)))

在我的实验中,对于大量“ block ”,这大约快两倍。

In [1]: %timeit [r for d in detections for r in d]
10000 loops, best of 3: 69.9 µs per loop

In [2]: %timeit list(chain.from_iterable(detections))
10000 loops, best of 3: 34 µs per loop

如果您实际上希望最终数据框中的索引反射(reflect)原始分组,您可以使用

pd.DataFrame(detections).stack().apply(pd.Series)
       Height  Left  Top  Width
0 0 86 1385 215 86
1 87 865 266 87
2 103 271 506 103
1 0 86 1385 215 86
1 87 865 266 87
2 103 271 506 103

你很接近,但你需要应用pd.Series堆叠索引之后。

关于python - 字典列表中的 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42304447/

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