从列表中的字典列表创建Pandas数据框架

8

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

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

这将产生:

堆叠的数据框

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

我如何将每个单元格中的字典转换为具有列“Left”、“Top”、“Width”、“Height”的行?


将列表展平的方法:https://dev59.com/qnNA5IYBdhLWcg3wdtld - greedy52
2个回答

17

除了 Psidom的回答,也可以使用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

如果你确实希望最终数据框中的索引反映原始分组,你可以通过以下方法实现:

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

谢谢Igor。最后一行正是我想要的。 - fierval

7
你可以通过循环列表来构建数据框的列表,然后将它们连接起来:
pd.concat([pd.DataFrame(d) for d in detections])

# Height    Left    Top  Width
#0    86    1385    215     86
#1    87     865    266     87
#2   103     271    506    103

或者先将列表展平,然后调用 pd.DataFrame()

pd.DataFrame([r for d in detections for r in d])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接