简体   繁体   English

python中字典值的加权平均值

[英]Weighted average of dictionary values in python

I have a grid of parameters which is composed of 234 dictionaries, everyone having the same keys. 我有一个由234个词典组成的参数网格,每个词典都有相同的键。 Then I have a list of weights through which I want to compute a weighted average of such dictionaries' values. 然后,我有一个权重列表,通过这些权重列表,我可以计算出这些字典值的加权平均值。 In other words I need to obtin just one dictionary that has the same keys of the initial 243, but as values attached to each keys a weighted average of values, using the 243 weights. 换句话说,我只需要处理一个字典,它具有与初始243相同的键,但是作为附加到每个键上的值,需要使用243权重进行加权平均。

I tried to use Counter in order to cumulate results, but it returns very small values that do not make sense to me. 我尝试使用Counter来累积结果,但是它返回的值非常小,对我来说没有意义。 w[0] is the list of 243 weights, each of them related to 243 dictionaries inside grid 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

Is there an easier way to implement it? 有没有更容易实现的方法?

You might want to use a defaultdict instead: 您可能要改用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))

Output: 输出:

defaultdict(<class 'int'>, {'V0': 19, 'rho': 18})

Notes: 笔记:

I have changed w so that you need to pass in a straight list. 我更改了w以便您需要直接输入清单。 You might want to call the function like this: avg_grid(grids, w[0]) 您可能想要这样调用函数: avg_grid(grids, w[0])

Also this doesn't produce an average as such. 同样,这不会产生平均值。 you may want to do a divide by len(grid) at some point. 您可能需要在某个时候除以len(grid)

Also for g,w in zip(grid, wgts): is a more pythonic iteration for g,w in zip(grid, wgts):是更具Python风格的迭代

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM