I have a dataframe like this in Pandas:
df = pd.DataFrame({
'org': ['A1', 'B1', 'A1', 'B2'],
'DIH': [True, False, True, False],
'Quantity': [10,20,10,20],
'Items': [1, 2, 3, 4]
})
Now I want to get the value counts and modal value of Quantity, but weighted by the number of Items.
So I know that I can do
df.groupby('Quantity').agg({'Items': 'sum'}).sort_values('Items', ascending=False)
And get this:
Quantity Items
20 6
10 4
But how do I get this as a percentage value, like this?
Quantity Items
20 60
10 40
This worked for me
df.groupby('Quantity').agg({'Items': 'sum'}).sort_values('Items', ascending=False)/df['Items'].sum()*100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With