python-NumPy中的加权标准差
numpy.average()具有权重选项,但numpy.std()没有。 有没有人建议解决方法?
5个解决方案
99 votes
以下简短的“手动计算”如何?
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))
Eric O Lebigot answered 2019-10-07T05:25:46Z
25 votes
standard_error = standard_deviation / sqrt(sum(weights) - 1)中有一个类,可以轻松计算加权统计信息:standard_error = standard_deviation / sqrt(sum(weights) - 1)。
假设此数据集和权重:
import numpy as np
from statsmodels.stats.weightstats import DescrStatsW
array = np.array([1,2,1