def weighted_avg_and_std(values, weights=None):
'''
Return the weighted average and standard deviation.
`values` - np.ndarray of values to average.
`weights` - Optional np.ndarray of weights. Otherwise all values are assumed
equally weighted.
Note the helpful np.fromiter() function, helpful building arrays.
'''
if not isinstance(values, np.ndarray):
raise TypeError("Values must be an np.array")
if len(values) == 0:
raise ValueError("Can't calculate with no values")
if weights is not None:
if not isinstance(weights, np.ndarray):
raise TypeError("Weights must be None or an np.array")
if len(values) != len(weights):
raise ValueError("Length of values and weights differ")
average = np.average(values, weights=weights)
variance = np.average((values-average)**2, weights=weights) # Fast and numerically precise
return (average, math.sqrt(variance))
评论列表
文章目录