嵌套字典中的平均值

时间:2015-01-23 03:12:00

标签: python python-2.7

我想创建一个新的值列表my_qty,其中每个项目等于d[key]['qty']d[key]['start date']my_dates中的值匹配的所有值的平均值}。我想我很接近,但是我被挂在了嵌套部分。

import datetime
import numpy as np
my_dates = [datetime.datetime(2014, 10, 12, 0, 0), datetime.datetime(2014, 10, 13, 0, 0), datetime.datetime(2014, 10, 14, 0, 0)]

d = {
    'ID1' : {'start date': datetime.datetime(2014, 10, 12, 0, 0) , 'qty': 12},
    'ID2' : {'start date': datetime.datetime(2014, 10, 13, 0, 0) , 'qty': 34},
    'ID3' : {'start date': datetime.datetime(2014, 10, 12, 0, 0) , 'qty': 35},
    'ID4' : {'start date': datetime.datetime(2014, 10, 11, 0, 0) , 'qty': 40},
}

my_qty = []
for item in my_dates:
  my_qty.append([np.mean(x for x in d[key]['qty']) if d[key]['start date'] == my_dates[item]])

print my_qty

期望的输出:

[23.5,34,0]

澄清每个请求的输出:

[average of d[key]['qty'] where d[key]['start date '] == my_dates[0], average of d[key]['qty'] where d[key]['start date '] == my_dates[1], average of d[key]['qty'] where d[key]['start date '] == my_dates[2],]

3 个答案:

答案 0 :(得分:5)

使用纯python

简单的方法是按日期将数量分组到字典中:

import collections

quantities = collections.defaultdict(lambda: [])

for k,v in d.iteritems():
    quantities[v["start date"]].append(v["qty"])

然后运行该字典来计算方法:

means = {k: float(sum(q))/len(q) for k,q in quantities.iteritems()}

,并提供:

>>> means
{datetime.datetime(2014, 10, 11, 0, 0): 40.0,
 datetime.datetime(2014, 10, 12, 0, 0): 23.5,
 datetime.datetime(2014, 10, 13, 0, 0): 34.0}

如果你想要聪明,可以通过保持当前的平均值和你已经看到的数值的数量来一次性计算均值。你甚至可以在课堂上抽象出来:

class RunningMean(object):
    def __init__(self, mean=None, n=0):
        self.mean = mean
        self.n = n

    def insert(self, other):
        if self.mean is None:
            self.mean = 0.0
        self.mean = (self.mean * self.n + other) / (self.n + 1)
        self.n += 1

    def __repr__(self):
        args = (self.__class__.__name__, self.mean, self.n)
        return "{}(mean={}, n={})".format(*args)

一次通过您的数据会给您答案:

import collections
means = collections.defaultdict(lambda: RunningMean())
for k,v in d.iteritems():
    means[v["start date"]].insert(v["qty"])

使用pandas

真正的简单方法是使用pandas库,因为它是为这样的事情而制作的。这是一些代码:

import pandas as pd
df = pd.DataFrame.from_dict(d, orient="index")
means = df.groupby("start date").aggregate(np.mean)

,并提供:

>>> means
             qty
start date      
2014-10-11  40.0
2014-10-12  23.5
2014-10-13  34.0

答案 1 :(得分:2)

一行回答:

mean_qty = [np.mean([i['qty'] for i in d.values()\
 if i.get('start date') == day] or 0) for day in my_dates] 

In [12]: mean_qty
Out[12]: [23.5, 34.0, 0.0]

or 0的目的是如果没有qty则返回0,因为空列表上的np.mean默认返回nan

如果你需要速度,那么建立在jme的优秀第二部分上,你可以做到这一点(我没有重新计算平均值,直到它被要求减少了3倍的时间):

class RunningMean(object):
    def __init__(self, total=0.0, n=0):
        self.total=total
        self.n = n

    def __iadd__(self, other):
        self.total += other
        self.n += 1
        return self

    def mean(self): 
        return (self.total/self.n if self.n else 0)

    def __repr__(self):
        return "RunningMean(total=%f, n=%i)" %(self.total, self.n)
means = defaultdict(RunningMean)
for v in d.values():
    means[v["start date"]] += (v["qty"])

Out[351]: 
[RunningMean(mean= 40.000000),
 RunningMean(mean= 34.000000),
 RunningMean(mean= 23.500000)]

答案 2 :(得分:1)

以下是一些可以帮助您的工作代码:

for item in my_dates:
  nums = [ d[key]['qty'] for key in d if d[key]['start date'] == item ]
  if len(nums):
    avg = np.mean(nums)
  else:
    avg = 0
  print item, nums, avg

请注意,np.mean不适用于空列表,因此您必须检查要平均的数字的长度。