【问题标题】:Average value in multiple dictionaries based on key in Python?基于Python中的键的多个字典中的平均值?
【发布时间】:2015-12-07 17:23:56
【问题描述】:

我有三个(或更多)字典:

A = {'a':1,'b':2,'c':3,'d':4,'e':5}
B = {'b':1,'c':2,'d':3,'e':4,'f':5}
C = {'c':1,'d':2,'e':3,'f':4,'g':5}

如何获取三个字典中每个键的平均值的字典?

例如,给定上述字典,输出将是:

{'a':1/1, 'b':(2+1)/2, 'c':(3+2+1)/3, 'd':(4+3+2)/3, 'e':(5+4+3)/3, 'f':(5+4)/2, 'g':5/1}

【问题讨论】:

  • 您使用的是哪个版本的 Python?
  • 如果这是您需要做一次的事情,我会使用下面的纯 Python 解决方案。如果您经常处理此类数据,那么从长远来看,使用 pandas 可能会有所收获。
  • 谢谢,我用过 pandas,它工作正常。

标签: python dictionary


【解决方案1】:

你可以使用Pandas,像这样:

import pandas as pd
df = pd.DataFrame([A,B,C])
answer = dict(df.mean())
print(answer)

【讨论】:

  • Pandas 不是内置模块。我不认为 OP 正在寻找这种解决方案。
【解决方案2】:

我使用 Counter 来解决这个问题。请尝试以下代码:)

from collections import Counter

A = {'a':1,'b':2,'c':3,'d':4,'e':5}
B = {'b':1,'c':2,'d':3,'e':4,'f':5}
C = {'c':1,'d':2,'e':3,'f':4,'g':5}

sums = Counter()
counters = Counter()
for itemset in [A, B, C]:
    sums.update(itemset)
    counters.update(itemset.keys())

ret = {x: float(sums[x])/counters[x] for x in sums.keys()}

print ret

【讨论】:

    【解决方案3】:

    最简单的方法是使用collections.Counter 解释here,像这样:

    from collections import Counter
    
    sums = dict(Counter(A) + Counter(B) + Counter(C))
    # Which is {'a': 1, 'c': 6, 'b': 3, 'e': 12, 'd': 9, 'g': 5, 'f': 9}
    
    means = {k: sums[k] / float((k in A) + (k in B) + (k in C)) for k in sums}
    

    结果是:

    >>> means
    {'a': 1.0, 'b': 1.5, 'c': 2.0, 'd': 3.0, 'e': 4.0, 'f': 4.5, 'g': 5.0}
    

    【讨论】:

      【解决方案4】:

      如果您使用的是 python 2.7 或 3.5,您可以使用以下内容:

      keys = set(A.keys()+B.keys()+C.keys())
      
      D = {key:(A.get(key,0)+B.get(key,0)+C.get(key,0))/float((key in A)+(key in B)+(key in C)) for key in keys}
      

      哪个输出

       D
      {'a': 1.0, 'c': 2.0, 'b': 1.5, 'e': 4.0, 'd': 3.0, 'g': 5.0, 'f': 4.5}
      

      如果您不想使用任何软件包。这在 python 2.6 及更低版本中不起作用。

      【讨论】:

        【解决方案5】:

        这是一种非常通用的方法(即您可以轻松更改为任何聚合函数)。:

        def aggregate_dicts(dicts, operation=lambda x: sum(x) / len(x)):
            """
            Aggregate a sequence of dictionaries to a single dictionary using `operation`. `Operation` should
            reduce a list of all values with the same key. Keyrs that are not found in one dictionary will
            be mapped to `None`, `operation` can then chose how to deal with those.
            """
            all_keys = set().union(*[el.keys() for el in dicts])
            return {k: operation([dic.get(k, None) for dic in dicts]) for k in all_keys}
        

        示例:

        dicts_diff_keys = [{'x': 0, 'y': 1}, {'x': 1, 'y': 2}, {'x': 2, 'y': 3, 'c': 4}]
        
        def mean_no_none(l):
            l_no_none = [el for el in l if el is not None]
            return sum(l_no_none) / len(l_no_none)
        
        aggregate_dicts(dicts_diff_keys, operation= mean_no_none)
        #{'x': 1.0, 'c': 4.0, 'y': 2.0}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多