How to sum values grouped by a categorical column in pandas?
<p>I have data which has a categorical column that groups the data and other columns likes this in a dataframe <code>df</code>.</p>

<pre><code>id      subid       value
 1        10         1.5
 1        20         2.5
 1        30         7.0 
 2        10         12.5
 2        40         5
</code></pre>

<p>What I need is a column that has the average value for each <code>subid</code> within each <code>id</code>. For example <code>df</code> could be, </p>

<pre><code>id      subid       value     id_sum   proportion
 1        10         1.5       11.0      0.136
 1        20         2.5       11.0      0.227
 1        30         7.0       11.0      0.636
 2        10         12.5      17.5      0.714
 2        40         5         17.5      0.285
</code></pre>

<p>Now, I tried getting the id_sum column by doing</p>

<pre><code>df['id_sum'] = df.groupby('id')['value'].sum()
</code></pre>

<p>But this does not seem to work as hoped. My end goal is to get the <code>proportion</code> column. What is the correct way of getting that?</p>

<p>here we go</p>

<pre><code>df['id_sum'] = df.groupby('id')['value'].transform('sum')
df['proportion'] = df['value'] / df['id_sum']
</code></pre>

python pandas aggregate