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><code>numpy.average</code> admits a <code>weights</code> argument:</p>

<pre><code>import io
import numpy as np
import pandas as pd

data = io.StringIO('''\
      weight       x     value
0          5     -8.7        2
1          9     -8.7        3
2         12    -21.4       10
3         32    -21.4       15
''')
df = pd.read_csv(data, delim_whitespace=True)

df.groupby('x').apply(lambda g: np.average(g['value'], weights=g['weight']))
</code></pre>

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>x
-21.4    13.636364
-8.7      2.642857
dtype: float64
</code></pre>

python pandas numpy