Reputation: 8247
I have following dataframe in pandas
Date Code ID Quantity
16-08-2018 156 1 10
16-08-2018 156 2 10
16-08-2018 156 3 10
16-08-2018 156 4 10
17-08-2018 157 1 30
17-08-2018 157 2 20
17-08-2018 157 3 30
17-08-2018 157 4 20
I want to calculate percentage share of ID with total Quantity group by Date and Code
. My desired dataframe would be
Date Code ID Quantity Perc
16-08-2018 156 1 10 25
16-08-2018 156 2 10 25
16-08-2018 156 3 10 25
16-08-2018 156 4 10 25
17-08-2018 157 1 30 30
17-08-2018 157 2 20 20
17-08-2018 157 3 30 30
17-08-2018 157 4 20 20
How can I do it in pandas?
Upvotes: 1
Views: 1612
Reputation: 164673
Using GroupBy
+ transform
with 'sum'
:
g = df.groupby(['Date', 'Code'])['Quantity'].transform('sum')
df['Perc'] = df['Quantity'] / g * 100
Result:
Date Code ID Quantity Perc
0 16-08-2018 156 1 10 25
1 16-08-2018 156 2 10 25
2 16-08-2018 156 3 10 25
3 16-08-2018 156 4 10 25
4 17-08-2018 157 1 30 30
5 17-08-2018 157 2 20 20
6 17-08-2018 157 3 30 30
7 17-08-2018 157 4 20 20
Upvotes: 1