Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created October 13, 2011 20:27
Show Gist options
  • Save pyrtsa/1285415 to your computer and use it in GitHub Desktop.
Save pyrtsa/1285415 to your computer and use it in GitHub Desktop.
mean(iterable)
def mean(iterable):
"""Find the mean value of the sequence (0 if empty). Consumes generators"""
if hasattr(iterable, '__len__'):
n = len(iterable)
return sum(iterable) / float(n) if n > 0 else 0.0
else:
sentinel, iterable = object(), iter(iterable)
n, s = 1, next(iterable, sentinel)
if s is sentinel: return 0.0
for x in iterable: n,s = n+1, s+x
return s / float(n)
def nanmean(iterable):
"""Find the mean but skip nan's, and return nan if there are no numbers"""
from itertools import chain
gen = (x for x in iterable if x == x)
try:
fst = next(gen)
return mean(chain([fst], gen))
except StopIteration: return float('nan')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment