【问题标题】:Pandas/numpy weighted average ZeroDivisionErrorPandas/numpy 加权平均 ZeroDivisionError
【发布时间】:2018-09-26 15:04:31
【问题描述】:

创建一个 lambda 函数来计算加权平均值并将其发送到字典。

wm = lambda x: np.average(x, weights=df.loc[x.index, 'WEIGHTS'])

# Define a dictionary with the functions to apply for a given column:
f = {'DRESS_AMT': 'max', 
     'FACE_AMT': 'sum',
     'Other_AMT': {'weighted_mean' : wm}}

# Groupby and aggregate with dictionary:
df2=df.groupby(['ID','COL1'], as_index=False).agg(f)

此代码有效,但如果权重加起来为 0 ZeroDivisionError,则加权平均 lambda 函数将失败。在这些情况下,我希望输出“Other_AMT”为 0。

我阅读了有关使用 np.ma.average(掩蔽平均值)的文档,但不明白如何实现它

【问题讨论】:

    标签: python pandas numpy divide-by-zero weighted-average


    【解决方案1】:

    这还不够吗?

    def wm(x):
        try: 
            return np.average(x, weights=df.loc[x.index, 'WEIGHTS'])
        except ZeroDivisionError:
            return 0
    
    f = {'DRESS_AMT': 'max', 
         'FACE_AMT': 'sum',
         'Other_AMT': {'weighted_mean' : wm} }
    
    df2=df.groupby(['ID','COL1'], as_index=False).agg(f)
    

    【讨论】:

      猜你喜欢
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 2012-06-06
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      相关资源
      最近更新 更多