Pandas Groupby 加权标准偏差

问题描述

我有一个数据框:

             Type Weights Value  ....
    0         W     0.5    15  
    1         C     1.2    19  
    2         W     12     25  
    3         C     7.1    15    .....
    .......
    .......

我想按类型分组,然后计算加权平均值加权标准差

似乎有解决加权平均值 (groupby weighted average and sum in pandas dataframe) 但没有加权标准差解决方案。

有没有简单的方法可以做到这一点。

解决方法

我使用了以下链接中的加权标准偏差公式: https://doc-archives.microstrategy.com/producthelp/10.7/FunctionsRef/Content/FuncRef/WeightedStDev__weighted_standard_deviation_of_a_sa.htm

但是你可以修改不同的公式

import numpy as np
def weighted_sd(input_df):
    weights = input_df['Weights']
    vals = input_df['Value']
    numer = np.sum(weights * (vals - vals.mean())**2)
    denom = ((vals.count()-1)/vals.count())*np.sum(weights)
    return np.sqrt(numer/denom)

print(df.groupby('Type').apply(weighted_sd))