[英]Weighted average of dictionary values in python
我有一個由234個詞典組成的參數網格,每個詞典都有相同的鍵。 然后,我有一個權重列表,通過這些權重列表,我可以計算出這些字典值的加權平均值。 換句話說,我只需要處理一個字典,它具有與初始243相同的鍵,但是作為附加到每個鍵上的值,需要使用243權重進行加權平均。
我嘗試使用Counter
來累積結果,但是它返回的值非常小,對我來說沒有意義。 w[0]
是243個權重的列表,每個權重與grid
內的243個詞典有關
from collections import Counter
def avg_grid(grid, w, labels=["V0", "omega", "kappa", "rho", "theta"]):
avgHeston = Counter({label: 0 for label in labels})
for i in range(len(grid)):
avgHeston.update(Counter({label: grid[i][label] * w[0][i] for label in labels}))
totPar = dict(avgHeston)
return totPar
有沒有更容易實現的方法?
您可能要改用defaultdict
:
from collections import defaultdict
def avg_grid(grid, wgts, labels=["V0", "rho"]):
avgHeston = defaultdict(int)
for g,w in zip(grid, wgts):
for label in labels:
avgHeston[label] += g[label] * w
return avgHeston
weights = [4,3]
grd = [{'V0':4,'rho':3}, {'V0':1,'rho':2}]
print(avg_grid(grd, weights))
輸出:
defaultdict(<class 'int'>, {'V0': 19, 'rho': 18})
筆記:
我更改了w
以便您需要直接輸入清單。 您可能想要這樣調用函數: avg_grid(grids, w[0])
同樣,這不會產生平均值。 您可能需要在某個時候除以len(grid)
。
也for g,w in zip(grid, wgts):
是更具Python風格的迭代
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.