来自字典列表列表的 Pandas DataFrame

2024-05-02

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

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

其产量:

这几乎就是我想要的but:

如何将每个单元格中的字典转换为包含“左”、“顶”、“宽度”、“高度”列的行?


要添加到普西多姆的回答 https://stackoverflow.com/a/42304526/1391671,列表也可以使用扁平化itertools.chain.from_iterable.

from itertools import chain

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

在我的实验中,对于大量“块”来说,速度大约是原来的两倍。

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

If you actually希望最终数据框中的索引反映原始分组,您可以使用以下命令来完成此操作

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 after堆叠索引。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

来自字典列表列表的 Pandas DataFrame 的相关文章

随机推荐