python - Pythonic way to calculate the mean and variance of values in Counters -
i'm wondering whether there pythonic way compute means , variances of counters?
for example, have 4 counters sharing same keys:
a = counter({1: 23, 2: 39, 3: 1}) b = counter({1: 28, 2: 39, 3: 1}) c = counter({1: 23, 2: 39, 3: 2}) d = counter({1: 23, 2: 22, 3: 1})
my way is:
each_key_val = {} in a.keys(): # assumption here counters must share same keys j in [a, b, c, d]: try: each_key_val[i].append(j[i]) except: each_key_val[i] = [j[i]]
i use following code find mean / variance each key:
np.mean(each_key_val[i]) np.var(each_key_val[i])
is there easier way compute mean / variance each key compared way?
it's not think following more readable have, uses list comprehensions.
say have
cs = (a, b, c, d)
then dictionary of mean can found with
m = {k: float(d) / len(cs) k, d in sum(cs).iteritems()}
for variance, note that, definition of variance v[x] = e[x2] - (e[x])2, so, if define:
p = sum([counter({k: ((float(d**2) / len(cs))) (k, d) in cn.iteritems()}) \ cn in cs])
then variance dictionary is
{k: p[k] - m[k]**2 k in m}
Comments
Post a Comment