Robin1988 Robin1988 - 2 months ago 10
SQL Question

Pandas/SQL-calculate the pecentage based on different Group

I want to calculate the percentage of each group and a new column
For example:
data=

Group Value
A 1
A 2
A 1
B 4
B 4
B 8


and I want to get:

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


How to get it with pandas function or SQL? Thanks!

Answer

Using pandas:

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

output:

  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