【发布时间】: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