Pandas/numpy Weighted Average Zerodivisionerror
Creating a lambda function to calculate weighted average and sending that to a dictionary. wm = lambda x: np.average(x, weights=df.loc[x.index, 'WEIGHTS']) # Define a dictionary
Solution 1:
Shouldn't this be enough?
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)
Post a Comment for "Pandas/numpy Weighted Average Zerodivisionerror"