Weighted percentile using numpy

Completely vectorized numpy solution Here is the code I use. It’s not an optimal one (which I’m unable to write with numpy), but still much faster and more reliable than accepted solution def weighted_quantile(values, quantiles, sample_weight=None, values_sorted=False, old_style=False): “”” Very close to numpy.percentile, but supports weights. NOTE: quantiles should be in [0, 1]! :param values: … Read more

Weighted standard deviation in NumPy

How about the following short “manual calculation”? def weighted_avg_and_std(values, weights): “”” Return the weighted average and standard deviation. values, weights — Numpy ndarrays with the same shape. “”” average = numpy.average(values, weights=weights) # Fast and numerically precise: variance = numpy.average((values-average)**2, weights=weights) return (average, math.sqrt(variance))