Skip to content Skip to sidebar Skip to footer

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), t

Solution 1:

Are you looking to group the weighted average by id ?

df.groupby('id').apply(lambda x: np.average(x['b'],weights=x['a'])).reset_index(name='Weighted Average')
Out[1]: 
   idWeightedAverage0223.8780491333.1666672520.975610

Or if you want to do the weighted average of a / b:

(df.groupby('id').apply(lambda x: np.average(x['a']/x['b'],weights=x['a']))
 .reset_index(name='Weighted Average'))
Out[2]: 
   id  Weighted Average
0   2          1.754146
1   3          1.504274
2   5          1.962528

Post a Comment for "Calculating Weighted Average In Pandas Using Numpy Function"