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')
如果您的日期列不是日期时间,那么您可以将其转换并按月分组,如下所示:
df.groupby(df['Date'].to_datetime().dt.month).apply(weight_avg, 'Column 1', 'Amount')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.