【问题标题】:Pandas Groupby Weighted Standard DeviationPandas Groupby 加权标准差
【发布时间】:2021-10-01 02:46:00
【问题描述】:

我有一个数据框:

             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) 的解决方案,但没有可用于加权标准差的解决方案

有没有简单的方法。

【问题讨论】:

    标签: pandas group-by pandas-groupby standard-deviation weighted


    【解决方案1】:

    我使用了以下链接中的加权标准差公式: 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))
    

    【讨论】:

      猜你喜欢
      • 2013-05-21
      • 1970-01-01
      • 2011-01-25
      • 2013-07-16
      • 2021-09-06
      • 2017-03-04
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多