Calculating weighted average in Pandas using NumPy function
问题 Assume we have a pandas dataframe like this: a b id 36 25 2 40 25 3 46 23 2 40 22 5 42 20 5 56 39 3 I would like to perform a operation (a div b), then group by id and finally calculate a weighted average, using "a" as weights. It work's when I only calculate the mean. import pandas as pd import numpy as np df = pd.read_csv('file', sep='\s+') a = (df['a'].div(df['b'])).groupby(df['id']).mean() # work fine b = (df['a'].div(df['b'])).groupby(df['dd']).apply(lambda x: np.average(x ??? ), weights