getting weighted average then grouping in pandas
<p>I have the following dataframe. </p>

<pre><code>      weight       x     value
0          5     -8.7        2
1          9     -8.7        3
2         12    -21.4       10
3         32    -21.4       15
</code></pre>

<p>I need to get weighted average of the value and grouped on x. Result will be:</p>

<p>-8.7: (5/(5+9) * 2) + ((9/14) * 3) = 2.64</p>

<p>-21.4: ((12/44) * 10) + ((32/44) * 15) = 13.63</p>

<pre><code>         x     weighted_value
0     -8.7               2.64
1    -21.4              13.63
</code></pre>

<p>Here's a vectorized approach using NumPy tools -</p>

<pre><code># Get weighted averages and corresponding unique x's
unq,ids = np.unique(df.x,return_inverse=True)
weight_avg = np.bincount(ids,df.weight*df.value)/np.bincount(ids,df.weight)

# Store into a dataframe
df_out = pd.DataFrame(np.column_stack((unq,weight_avg)),columns=['x','wghts'])
</code></pre>

<p>Sample run -</p>

<pre><code>In [97]: df
Out[97]: 
   weight     x  value
0       5  -8.7      2
1       9  -8.7      3
2      12 -21.4     10
3      32 -21.4     15

In [98]: df_out
Out[98]: 
      x      wghts
0 -21.4  13.636364
1  -8.7   2.642857
</code></pre>

python pandas numpy