def _nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): # Using array() instead of asanyarray() because the former always # makes a copy, which is important due to the copyto() action later arr = array(a, subok=True) mask = isnan(arr) # First compute the mean, saving 'rcount' for reuse later if dtype is None and (issubdtype(arr.dtype, nt.integer) or issubdtype(arr.dtype, nt.bool_)): arrmean = um.add.reduce(arr, axis=axis, dtype='f8', keepdims=True) else: mu.copyto(arr, 0.0, where=mask) arrmean = um.add.reduce(arr, axis=axis, dtype=dtype, keepdims=True) rcount = (~mask).sum(axis=axis, keepdims=True) if isinstance(arrmean, mu.ndarray): arrmean = um.true_divide(arrmean, rcount, out=arrmean, casting='unsafe', subok=False) else: arrmean = arrmean / float(rcount) # arr - arrmean x = arr - arrmean mu.copyto(x, 0.0, where=mask) # (arr - arrmean) ** 2 if issubdtype(arr.dtype, nt.complex_): x = um.multiply(x, um.conjugate(x), out=x).real else: x = um.multiply(x, x, out=x) # add.reduce((arr - arrmean) ** 2, axis) ret = um.add.reduce(x, axis=axis, dtype=dtype, out=out, keepdims=keepdims) # add.reduce((arr - arrmean) ** 2, axis) / (n - ddof) if not keepdims and isinstance(rcount, mu.ndarray): rcount = rcount.squeeze(axis=axis) rcount -= ddof if isinstance(ret, mu.ndarray): ret = um.true_divide(ret, rcount, out=ret, casting='unsafe', subok=False) else: ret = ret / float(rcount) return ret
def _nanmean(a, axis=None, dtype=None, out=None, keepdims=False): # Using array() instead of asanyarray() because the former always # makes a copy, which is important due to the copyto() action later arr = array(a, subok=True) mask = isnan(arr) # Cast bool, unsigned int, and int to float64 if dtype is None and (issubdtype(arr.dtype, nt.integer) or issubdtype(arr.dtype, nt.bool_)): ret = um.add.reduce(arr, axis=axis, dtype='f8', out=out, keepdims=keepdims) else: mu.copyto(arr, 0.0, where=mask) ret = um.add.reduce(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims) rcount = (~mask).sum(axis=axis) if isinstance(ret, mu.ndarray): ret = um.true_divide(ret, rcount, out=ret, casting='unsafe', subok=False) else: ret = ret / float(rcount) return ret