Pandas/numpy 加权平均 ZeroDivisionError

2024-02-08

创建 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,则加权平均 lambda 函数会失败ZeroDivisionError。在这些情况下,我希望输出“Other_AMT”仅为 0。

我阅读了有关使用 np.ma.average (屏蔽平均值)的文档,但无法理解如何实现它


这还不够吗?

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas/numpy 加权平均 ZeroDivisionError 的相关文章

随机推荐