Calculate the weighted mean of an array/list using numpy.
770348
def numpy_weighted_mean(data, weights=None):
    """"""
    import numpy as np
    weights = np.array(weights).flatten() / float(sum(weights))
    return np.dot(np.array(data), weights)
1231844
def mean(series):
    

    if np.issubdtype(series.dtype, np.number):
        return series.mean()
    else:
        return np.nan
1320166
def gmean(x, weights=None):
    
    w_arr, x_arr = _preprocess_inputs(x, weights)
    return np.exp((w_arr*np.log(x_arr)).sum(axis=0) / w_arr.sum(axis=0))
771995
def weighted_n(self):
        """"""
        if not self.is_weighted:
            return float(self.unweighted_n)
        return float(sum(self._cube_dict["result"]["measures"]["count"]["data"]))
567372
def hmean(x, weights=None):
    
    w_arr, x_arr = _preprocess_inputs(x, weights)
    return w_arr.sum(axis=0) / (w_arr/x_arr).sum(axis=0)
1049287
def _weighted_selection(l, n):
    
    cuml = []
    items = []
    total_weight = 0.0
    for weight, item in l:
        total_weight += weight
        cuml.append(total_weight)
        items.append(item)

    return [items[bisect.bisect(cuml, random.random()*total_weight)] for _ in range(n)]
1041715
def average_weights(self):
        """"""
        for feat, weights in self.weights.items():
            new_feat_weights = {}
            for clas, weight in weights.items():
                param = (feat, clas)
                total = self._totals[param]
                total += (self.i - self._tstamps[param]) * weight
                averaged = round(total / float(self.i), 3)
                if averaged:
                    new_feat_weights[clas] = averaged
            self.weights[feat] = new_feat_weights
        return None
999083
def individual_weights(self):
        
        weights = self._raw_weights()
        if weights.shape[1] == 0:
            return np.zeros(weights.shape[0])
        elif weights.shape[1] < self._ntaps:
            return np.mean(weights, axis=1)
        else:
            return weights.dot(self._filter_coeffs)
335541
def mean
      mean = Pair.new(0, 0)
      weight = 0

      objects.each do |object, n|
        (1..n).each do |_i|
          mean + object
          weight += 1
        end
      end
      mean / weight
      mean
    end
728607
def sse(mean, estimator):
    
    return np.sum((np.asarray(estimator) - np.asarray(mean)) ** 2, axis=0)
244474
def _wva(values, weights):
        
        assert len(values) == len(weights) and len(weights) > 0
        return sum([mul(*x) for x in zip(values, weights)]) / sum(weights)
332407
def mean(array):
    
    n = len(array)

    if n < 1:
        return 0
    elif n == 1:
        return array[0]
    return sum(array) / n
813175
def weighted_median(data, weights=None):
    """"""
    if weights is None:
        return median(data)
    midpoint = 0.5 * sum(weights)
    if any([j > midpoint for j in weights]):
        return data[weights.index(max(weights))]
    if any([j > 0 for j in weights]):
        sorted_data, sorted_weights = zip(*sorted(zip(data, weights)))
        cumulative_weight = 0
        below_midpoint_index = 0
        while cumulative_weight <= midpoint:
            below_midpoint_index += 1
            cumulative_weight += sorted_weights[below_midpoint_index-1]
        cumulative_weight -= sorted_weights[below_midpoint_index-1]
        if cumulative_weight - midpoint < sys.float_info.epsilon:
            bounds = sorted_data[below_midpoint_index-2:below_midpoint_index]
            return sum(bounds) / float(len(bounds))
        return sorted_data[below_midpoint_index-1]
1024687
def var(inlist):
    
    n = len(inlist)
    mn = mean(inlist)
    deviations = [0] * len(inlist)
    for i in range(len(inlist)):
        deviations[i] = inlist[i] - mn
    return ss(deviations) / float(n - 1)
655214
def estimate_column_means(
            self,
            X,
            observed,
            row_means,
            row_scales):
        
        n_rows, n_cols = X.shape
        row_means = np.asarray(row_means)

        if len(row_means) != n_rows:
            raise ValueError("Expected length %d but got shape %s" % (
                n_rows, row_means.shape))
        column_means = np.zeros(n_cols, dtype=X.dtype)

        X = X - row_means.reshape((n_rows, 1))
        row_weights = 1.0 / row_scales
        X *= row_weights.reshape((n_rows, 1))
        col_residual_sums = np.nansum(X, axis=0)
        for j in range(n_cols):
            col_mask = observed[:, j]
            sum_weights = row_weights[col_mask].sum()
            column_means[j] = col_residual_sums[j] / sum_weights
        return column_means
1337556
def _weighting(weights, exponent):
    """"""
    if np.isscalar(weights):
        weighting = NumpyTensorSpaceConstWeighting(weights, exponent)
    elif weights is None:
        weighting = NumpyTensorSpaceConstWeighting(1.0, exponent)
    else:  # last possibility: make an array
        arr = np.asarray(weights)
        weighting = NumpyTensorSpaceArrayWeighting(arr, exponent)
    return weighting
238341
def mean(array, axis=None, skipna=None, **kwargs):
    """"""
    from .common import _contains_cftime_datetimes

    array = asarray(array)
    if array.dtype.kind in 'Mm':
        offset = min(array)
        # xarray always uses np.datetime64[ns] for np.datetime64 data
        dtype = 'timedelta64[ns]'
        return _mean(datetime_to_numeric(array, offset), axis=axis,
                     skipna=skipna, **kwargs).astype(dtype) + offset
    elif _contains_cftime_datetimes(array):
        if isinstance(array, dask_array_type):
            raise NotImplementedError(
                'Computing the mean of an array containing '
                'cftime.datetime objects is not yet implemented on '
                'dask arrays.')
        offset = min(array)
        timedeltas = datetime_to_numeric(array, offset, datetime_unit='us')
        mean_timedeltas = _mean(timedeltas, axis=axis, skipna=skipna,
                                **kwargs)
        return _to_pytimedelta(mean_timedeltas, unit='us') + offset
    else:
        return _mean(array, axis=axis, skipna=skipna, **kwargs)