I'm trying to create a new column with Monthly weighted average.
I tried a few options but the weighted average calculation is taking total of column Amount
. for example in March 2021 because there is just one value, WA should be 10*(110/100), most code calculate 10*(110/total Amount column)
Any idea how to do this?
My Data:
Date | Column 1 | Amount | (Expected Output) Monthly WA |
---|---|---|---|
01-Jan-2021 | 20 | 100 | 16.78 |
01-Jan-2021 | 25 | 110 | 16.78 |
01-Jan-2021 | 15 | 120 | 16.78 |
01-Jan-2021 | 30 | 135 | 16.78 |
02-Jan-2021 | 10 | 150 | 16.78 |
02-Jan-2021 | 12 | 160 | 16.78 |
02-Jan-2021 | 11 | 175 | 16.78 |
01-Feb-2021 | 13 | 225 | 20.09 |
01-Feb-2021 | 15 | 220 | 20.09 |
01-Feb-2021 | 17 | 158 | 20.09 |
02-Feb-2021 | 20 | 185 | 20.09 |
02-Feb-2021 | 25 | 170 | 20.09 |
02-Feb-2021 | 35 | 160 | 20.09 |
01-Mar-2021 | 10 | 110 | 10 |
Here's the code I've tried:
def weight_avg(df, value, weights):
x = df[value]
y = df[weights]
return (x*y).sum()/y.sum() <br />
df.groupby(df['Date']).apply(weight_avg, 'Column 1', 'Amount')