weighted

Weighted percentile using numpy

a 夏天 提交于 2019-11-26 19:45:14
问题 Is there a way to use the numpy.percentile function to compute weighted percentile? Or is anyone aware of an alternative python function to compute weighted percentile? thanks! 回答1: Unfortunately, numpy doesn't have built-in weighted functions for everything, but, you can always put something together. def weight_array(ar, weights): zipped = zip(ar, weights) weighted = [] for i in zipped: for j in range(i[1]): weighted.append(i[0]) return weighted np.percentile(weight_array(ar, weights), 25)

Weighted standard deviation in NumPy

梦想的初衷 提交于 2019-11-26 18:31:12
numpy.average() has a weights option, but numpy.std() does not. Does anyone have suggestions for a workaround? 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)) There is a class in statsmodels that makes it easy to calculate weighted statistics: statsmodels