I have a sample data frame that looks like below (4*43). I would like to group_by "id" and then calculate the weighted mean for each column (0,1,2,...40) by "length". How should I go about combining group_by with the weighted mean calculation?
id length 0 1 2 3 .... 40
1 10 0.1 0.02 0.7 0.1 .. 0.4
1 5 0.2 0.01 0.1 0.4 ... 0.1
3 6 0.1 0.05. 0.2 0.5 ... 0.05
3 5 0.5 0.7 0.6 0.5 ... 0.8
I tried to use the group by function as below to get just the grouped average, but it failed to work.
df.groupby("id", as_index=True).mean().iloc[3:43]
Ideal output:
id weighted_0 weighted_1 weighted_2 .... weighted_40
1
3