I have a dataframe like below
Class| Student| V1| V2| V3| wb
A| Max| 10| 12| 14| 1
A| Ann| 9| 6| 7| 0.9
B| Tom| 6| 7| 10| 0.3
B| Dick| 3| 8| 7| 0.7
C| Dibs| 5| 2| 3| 0.8
C| Mock| 6| 4| 3| 0.6
D| Sunny| 3| 4| 5| 0.9
D| Lock| 8| 3| 6| 1
And i want to calculate the Weighted Mean for V1,V2,V3 grouped by Class the result should be something like below
Class V1_M V2_M V3_M
A 9 8 3
B 5 3 3
C 4 4 3
So far i can separate data frame for each column. But i feel very inefficient
And here is code for 1 variable
import pandas as pd
import numpy as np
def wtdavg(frame, var, wb):
d = frame[var]
w = frame[wb]
return (d * w).sum() / w.sum()
df = pd.read_csv('Sample.csv')
Matrix = df.groupby(['Class']).apply(wtdavg,var='V2',wb='wb')
print(Matrix)
I am a newbie with 1 week of pandas experience. Thanks in advance.
Max