[英]Pandas DataFrame from list of lists of dicts
我有一個數據結構,它是一個dicts列表列表:
[
[{'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())
產量:
這幾乎是我想要的, 但是 :
如何將每個單元格中的字典轉換為“左”,“頂”,“寬”,“高”列?
要添加到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
。
您可以循環遍歷列表,構建數據框列表,然后將它們連接起來:
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])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.