Pandas/SQL-calculate the pecentage based on different Group
<p>I want to calculate the percentage of each group and a new column
For example:
data=</p>

<pre><code>Group  Value   
  A     1
  A     2
  A     1
  B     4
  B     4
  B     8
</code></pre>

<p>and I want to get:</p>

<pre><code>Group  Value   Percentage
  A     1         0.25
  A     2         0.50
  A     1         0.25
  B     4         0.25
  B     4         0.25
  B     8         0.50
</code></pre>

<p>How to get it with pandas function or SQL? Thanks!</p>

<p>Using pandas:</p>

<pre><code>df['Percentage'] = df.groupby('Group')['Value'].transform(lambda x: x / x.sum())
</code></pre>

<p>output:</p>

<pre><code>  Group  Value  Percentage
0     A      1        0.25
1     A      2        0.50
2     A      1        0.25
3     B      4        0.25
4     B      4        0.25
5     B      8        0.50
</code></pre>

python sql pandas dataframe