![](/img/trans.png)
[英]How to find average value for netCDF over entire time period recorded in dataset (Python)?
[英]Python - Fastest way to find the average value over entire dict each time it gets modified?
我正试图找到从字典中提取平均值的最快/最有效的方法。 我正在处理的任务要求它执行数千次,所以每次只需迭代dict中的所有值,找到平均值就完全没有效率。 数以百计的新键值对被添加到字典中,我们需要在每次发生时找到平均值。 我们还需要在每次更新值时找到新的平均值,这会发生数千次。
在此先感谢 - 这是一个非常棒的地方。
创建自己的dict子类来跟踪计数和总数,然后可以快速返回平均值:
class AvgDict(dict):
def __init__(self):
self._total = 0.0
self._count = 0
def __setitem__(self, k, v):
if k in self:
self._total -= self[k]
self._count -= 1
dict.__setitem__(self, k, v)
self._total += v
self._count += 1
def __delitem__(self, k):
v = self[k]
dict.__delitem__(self, k)
self._total -= v
self._count -= 1
def average(self):
if self._count:
return self._total/self._count
a = AvgDict()
assert a.average() is None
a[1] = 1
assert a.average() == 1
a[2] = 10
assert a.average() == 5.5
assert a[2] == 10
a[1] = 5
assert a.average() == 7.5
del a[1]
assert a.average() == 10
以下是基于运行平均值,因此如果您知道以前的平均值:
At = (A0 * N + E) / (N + 1)
At is the average after addition of the new element
A0 is the average before addition of the new element
N is the number of element before addition of the new element
E is the new element's value
如果你保留元素总和的标签,它更简单的兄弟工作:
At = (T + E) / (N + 1)
T is the total of all elements
A0 is the average before addition of the new element
N is the number of element before addition of the new element
E is the new element's value
删除值时,您可以执行类似的操作:
At = (A0 * N - E) / (N - 1)
当值更新时:
At = (A0 * N - E0 + E1) / (N)
E0 is value before updating, E1 is value after updating.
从dict
继承并在每次调用__setitem__
计算平均值。
由于您可以将先前的平均值存储在字典类中并且仅对此平均值和添加的新值进行平均,这应该非常快 - 第一次添加新项目时,平均值就是该值的平均值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.