我有一個 python 字典串列,我正在嘗試根據不同的指標(最大值、最小值)聚合鍵。
現在,我正在將字典串列轉換為pandas資料框,然后使用該agg函式回傳我想要的輸出。
但是這樣做會引入一些時間和記憶體使用。在不求助于 pandas 的情況下提高運行時效率方面將不勝感激。
到目前為止我做了什么?
boxes = [{'width': 178.25, 'right': 273.25, 'top': 535.0, 'left': 95.0, 'bottom': 549.0, 'height': 14.0}, {'width': 11.17578125, 'right': 87.17578125, 'top': 521.0, 'left': 76.0, 'bottom': 535.0, 'height': 14.0}, {'width': 230.8515625, 'right': 306.8515625, 'top': 492.0, 'left': 76.0, 'bottom': 506.0, 'height': 14.0}, {'width': 14.65234375, 'right': 90.65234375, 'top': 535.0, 'left': 76.0, 'bottom': 549.0, 'height': 14.0}, {'width': 7.703125, 'right': 83.703125, 'top': 506.0, 'left': 76.0, 'bottom': 520.0, 'height': 14.0}, {'width': 181.8515625, 'right': 276.8515625, 'top': 521.0, 'left': 95.0, 'bottom': 535.0, 'height': 14.0}, {'width': 211.25, 'right': 306.25, 'top': 506.0, 'left': 95.0, 'bottom': 520.0, 'height': 14.0}]
boxes = pd.DataFrame(boxes)
boxes = boxes.agg({'left': min, 'right': max, 'top': min, 'bottom': max})
boxes['height'] = boxes['bottom'] - boxes['top']
boxes['width'] = boxes['right'] - boxes['left']
res = boxes.to_dict()
期望的結果
{'left': 76.0, 'right': 306.8515625, 'top': 492.0, 'bottom': 549.0, 'height': 57.0, 'width': 230.8515625}
uj5u.com熱心網友回復:
這是一種方法:
(i)dict.setdefault用于合并字典以創建單個字典temp
(ii) 遍歷temp并將函式應用functions到相應鍵的值上。
(iii) 'height' 和 'width' 不在functions. 分別計算它們。
functions = {'left': min, 'right': max, 'top': min, 'bottom': max}
temp = {}
for d in boxes:
for k, v in d.items():
if k in functions:
temp.setdefault(k, []).append(v)
out = {k: functions[k](v) for k, v in temp.items()}
out['height'] = out['bottom'] - out['top']
out['width'] = out['right'] - out['left']
輸出:
{'width': 230.8515625,
'right': 306.8515625,
'top': 492.0,
'left': 76.0,
'bottom': 549.0,
'height': 57.0}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410021.html
標籤:
